C# 中利用 CRC32 值判断文件是否重复

时间:2022-10-27 02:22:14

需要在 NuGet 中引用 Crc32.NET 包

直接贴代码了:

using Force.Crc32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Crc32NETDemo.ConApp.Codes; namespace Crc32NETDemo.ConApp
{
class Program
{
static void Main(string[] args)
{
string folderPath = @"D:\music\";
Console.WriteLine(string.Format("正在分析路径 {0} 下的文件的 CRC32 值。", folderPath));
IEnumerable<string> filePathList = Directory.EnumerateFiles(folderPath, "*", SearchOption.AllDirectories);
Dictionary<string, uint> dic = new Dictionary<string, uint>();
foreach (string filePath in filePathList)
{
byte[] zipdata = File.ReadAllBytes(filePath);
uint crc = Crc32CAlgorithm.Compute(zipdata);
dic.Add(filePath, crc);
} Console.WriteLine("重复的文件如下:" + Environment.NewLine);
IEnumerable<uint> doubledCrc32List = dic.Values.Iterative();
if (doubledCrc32List.Any())
{
var tempList = dic.Where(c => doubledCrc32List.Contains(c.Value)).OrderBy(c => c.Value).ToList();
foreach (var item in tempList)
{
Console.WriteLine(string.Format("路径:{0}, CRC32 值:{1}", item.Key, item.Value));
}
}
else
{
Console.WriteLine("没有找到重复的文件!");
}
Console.WriteLine();
Console.ReadLine();
}
}
}

谢谢浏览!