Program.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.IO.Enumeration;
  2. using System.Security.Cryptography;
  3. if (args.Length < 2)
  4. {
  5. Console.WriteLine("Usage: HashSumJ <algo> <dir-tree-to-checksum> [parallel:default same to vCpu]");
  6. Console.WriteLine(" algo: MD5 SHA256 SHA512 SHA1");
  7. return -1;
  8. }
  9. Func<string, string> hashAlgo = args[0].ToLower() switch
  10. {
  11. "md5" => MakeMd5FromFilePath,
  12. "sha256" => MakeSha256FromFilePath,
  13. "sha512" => MakeSha512FromFilePath,
  14. "sha1" => MakeSha1FromFilePath,
  15. _ => throw new ArgumentException("algo")
  16. };
  17. var dirToCheckSum = args[1];
  18. var threads = Environment.ProcessorCount;
  19. if (args.Length > 1 && ushort.TryParse(args[1], out var t)) threads = t;
  20. var files = new FileSystemEnumerable<string>(dirToCheckSum, (ref FileSystemEntry p) => p.ToFullPath(),
  21. new EnumerationOptions { RecurseSubdirectories = true, })
  22. { ShouldIncludePredicate = (ref FileSystemEntry p) => p.IsDirectory == false };
  23. var arrFilesPath = files.ToArray();
  24. var num = 0;
  25. Parallel.ForEach(arrFilesPath,
  26. new ParallelOptions { MaxDegreeOfParallelism = threads },
  27. f =>
  28. {
  29. try
  30. {
  31. Console.WriteLine($"{hashAlgo(f)}|{f}|t#{Environment.CurrentManagedThreadId}|{Interlocked.Increment(ref num)} of {arrFilesPath.Length}");
  32. }
  33. catch (Exception e)
  34. {
  35. Console.WriteLine($"Err: {e.Message}");
  36. }
  37. });
  38. return 0;
  39. static string MakeMd5FromFilePath(string filePath)
  40. {
  41. using var fs = File.OpenRead(filePath);
  42. return Convert.ToHexString(MD5.HashData(fs));
  43. }
  44. static string MakeSha1FromFilePath(string filePath)
  45. {
  46. using var fs = File.OpenRead(filePath);
  47. return Convert.ToHexString(SHA1.HashData(fs));
  48. }
  49. static string MakeSha256FromFilePath(string filePath)
  50. {
  51. using var fs = File.OpenRead(filePath);
  52. return Convert.ToHexString(SHA256.HashData(fs));
  53. }
  54. static string MakeSha512FromFilePath(string filePath)
  55. {
  56. using var fs = File.OpenRead(filePath);
  57. return Convert.ToHexString(SHA512.HashData(fs));
  58. }