77 lines
2.4 KiB
C#
77 lines
2.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace DuplicateFinder
|
|
{
|
|
internal class Program
|
|
{
|
|
private static string CalculateSha1(string filePath)
|
|
{
|
|
using (var sha1 = SHA1.Create())
|
|
{
|
|
using (var stream = File.OpenRead(filePath))
|
|
{
|
|
byte[] hashBytes = sha1.ComputeHash(stream);
|
|
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
|
|
}
|
|
}
|
|
}
|
|
|
|
static string GetValidDirectoryPath()
|
|
{
|
|
Console.Write("Enter directory path: ");
|
|
string path = Console.ReadLine().Trim();
|
|
if (!Directory.Exists(path))
|
|
{
|
|
Console.WriteLine("The directory does not exist. Please try again.");
|
|
return GetValidDirectoryPath();
|
|
}
|
|
Console.WriteLine();
|
|
return path;
|
|
}
|
|
|
|
static void Main(string[] args)
|
|
{
|
|
string directoryPath = GetValidDirectoryPath();
|
|
|
|
Dictionary<string, List<string>> fileHashes = new Dictionary<string, List<string>>();
|
|
foreach (string filePath in Directory.EnumerateFiles(directoryPath, "*.*", SearchOption.AllDirectories))
|
|
{
|
|
Console.WriteLine("Calculating hash: " + filePath);
|
|
string hash = CalculateSha1(filePath);
|
|
if (fileHashes.ContainsKey(hash))
|
|
{
|
|
fileHashes[hash].Add(filePath);
|
|
}
|
|
else
|
|
{
|
|
fileHashes[hash] = new List<string> { filePath };
|
|
}
|
|
}
|
|
|
|
if (fileHashes.Values.Count(v => v.Count > 1) > 1)
|
|
{
|
|
Console.WriteLine("\nDuplicate files:");
|
|
foreach (List<string> group in fileHashes.Values.Where(v => v.Count > 1))
|
|
{
|
|
foreach (string filePath in group)
|
|
{
|
|
Console.WriteLine(filePath);
|
|
}
|
|
Console.WriteLine();
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine("\nDuplicates not find.");
|
|
}
|
|
|
|
Console.WriteLine("Press any key to exit...");
|
|
Console.ReadKey();
|
|
}
|
|
}
|
|
}
|