MovieHasher.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace OpenSubtitlesHandler
  8. {
  9. public class MovieHasher
  10. {
  11. public static byte[] ComputeMovieHash(string filename)
  12. {
  13. byte[] result;
  14. using (Stream input = File.OpenRead(filename))
  15. {
  16. result = ComputeMovieHash(input);
  17. }
  18. return result;
  19. }
  20. private static byte[] ComputeMovieHash(Stream input)
  21. {
  22. long lhash, streamsize;
  23. streamsize = input.Length;
  24. lhash = streamsize;
  25. long i = 0;
  26. byte[] buffer = new byte[sizeof(long)];
  27. while (i < 65536 / sizeof(long) && (input.Read(buffer, 0, sizeof(long)) > 0))
  28. {
  29. i++;
  30. lhash += BitConverter.ToInt64(buffer, 0);
  31. }
  32. input.Position = Math.Max(0, streamsize - 65536);
  33. i = 0;
  34. while (i < 65536 / sizeof(long) && (input.Read(buffer, 0, sizeof(long)) > 0))
  35. {
  36. i++;
  37. lhash += BitConverter.ToInt64(buffer, 0);
  38. }
  39. input.Close();
  40. byte[] result = BitConverter.GetBytes(lhash);
  41. Array.Reverse(result);
  42. return result;
  43. }
  44. public static string ToHexadecimal(byte[] bytes)
  45. {
  46. StringBuilder hexBuilder = new StringBuilder();
  47. for (int i = 0; i < bytes.Length; i++)
  48. {
  49. hexBuilder.Append(bytes[i].ToString("x2"));
  50. }
  51. return hexBuilder.ToString();
  52. }
  53. }
  54. }