在C#中,要删除重复文件,可以使用以下方法:
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static string CalculateHash(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] bytes = sha256.ComputeHash(fs);
StringBuilder builder = new StringBuilder();
foreach (byte b in bytes)
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
}
}
using System.Collections.Generic;
public static void RemoveDuplicateFiles(string directoryPath)
{
Dictionary<string, List<string>> fileHashes = new Dictionary<string, List<string>>();
// 遍历目录中的所有文件
foreach (string filePath in Directory.GetFiles(directoryPath))
{
string hash = CalculateHash(filePath);
// 如果哈希值已经在字典中,将文件路径添加到对应的列表中
if (fileHashes.ContainsKey(hash))
{
fileHashes[hash].Add(filePath);
}
// 否则,创建一个新的键值对
else
{
fileHashes[hash] = new List<string> { filePath };
}
}
// 删除重复的文件
foreach (var entry in fileHashes)
{
List<string> duplicateFiles = entry.Value;
if (duplicateFiles.Count > 1)
{
Console.WriteLine($"Deleting duplicate files with hash {entry.Key}:");
foreach (string duplicateFilePath in duplicateFiles)
{
try
{
File.Delete(duplicateFilePath);
Console.WriteLine($"Deleted: {duplicateFilePath}");
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting {duplicateFilePath}: {ex.Message}");
}
}
}
}
}
RemoveDuplicateFiles
方法并传入要检查的目录路径。string directoryPath = @"C:\path\to\your\directory";
RemoveDuplicateFiles(directoryPath);
这将删除指定目录中的所有重复文件。请注意,这个方法只会删除重复的文件,而不会删除原始文件。如果你需要保留原始文件,可以在删除之前添加一个条件来检查文件名是否已经存在于目标目录中。