Advertisement
ivandrofly

Duplicate files remover

Mar 3rd, 2022 (edited)
1,777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.76 KB | None | 0 0
  1. using System.Security.Cryptography;
  2.  
  3.  
  4. var files = Directory.GetFiles(@"G:\My Drive\");
  5.  
  6.  
  7. var groupByLength = files.GroupBy(file => new FileInfo(file).Length)
  8.     .Where(gp => gp.Count() > 1).ToList();
  9.  
  10. foreach (var fileByLength in groupByLength)
  11. {
  12.     var byLength = fileByLength.OrderBy(name => name.Length).ToList();
  13.     string pivotFile = byLength.First();
  14.     var pivot = Md5(pivotFile);
  15.     foreach (var s in byLength.Skip(1))
  16.     {
  17.         if (pivot.SequenceEqual(Md5(s)))
  18.         {
  19.             Console.WriteLine($"{s} is duplicated {pivotFile}");
  20.             File.Delete(s);
  21.         }
  22.     }
  23. }
  24.  
  25. static byte[] Md5(string file)
  26. {
  27.     using var md5 = MD5.Create();
  28.     using var stream = File.OpenRead(file);
  29.     return md5.ComputeHash(stream);
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement