如何在C#中获取目录所有文件哈希值并存入Dictionary且显示进度
目录文件哈希计算及进度显示实现
以下是基于C#的实现方案,可将目录下所有文件的哈希值(支持SHA256/SHA512)存入Dictionary<string, string>,同时实时显示处理进度:
核心代码实现
using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; class FileHashProcessor { static void Main(string[] args) { // 替换为目标目录路径 string targetDir = @"D:\Your\Files\Directory"; var allFiles = Directory.GetFiles(targetDir); int totalFileCount = allFiles.Length; if (totalFileCount == 0) { Console.WriteLine("目标目录下无文件"); return; } // 初始化字典,指定容量提升性能 Dictionary<string, string> fileHashMap = new Dictionary<string, string>(totalFileCount); int processedCount = 0; // 选择哈希算法:SHA256.Create() 或 SHA512.Create() using (var hashAlgorithm = SHA256.Create()) { foreach (string filePath in allFiles) { try { string hashValue = ComputeFileHash(filePath, hashAlgorithm); fileHashMap.Add(filePath, hashValue); } catch (IOException ex) { Console.WriteLine($"\n文件读取失败:{filePath} - {ex.Message}"); } catch (UnauthorizedAccessException ex) { Console.WriteLine($"\n无权限访问文件:{filePath} - {ex.Message}"); } finally { processedCount++; // 计算进度并覆盖行输出,避免刷屏 int progressPercent = (int)Math.Round((double)processedCount / totalFileCount * 100); Console.SetCursorPosition(0, Console.CursorTop); Console.Write($"进度:{progressPercent}% | 已处理 {processedCount}/{totalFileCount} 个文件"); } } } Console.WriteLine("\n\n哈希计算完成,结果已存入Dictionary:"); // 示例:输出前5个文件的哈希值 int displayCount = 0; foreach (var entry in fileHashMap) { if (displayCount >=5) break; Console.WriteLine($"{entry.Key}\n哈希值:{entry.Value}\n"); displayCount++; } } /// <summary> /// 计算单个文件的哈希值 /// </summary> private static string ComputeFileHash(string filePath, HashAlgorithm hashAlgorithm) { // 以共享读写模式打开文件,避免文件被占用时抛出异常 using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { byte[] hashBytes = hashAlgorithm.ComputeHash(fileStream); // 将字节数组转换为小写十六进制字符串 return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); } } }
关键说明
- 进度显示:通过
Console.SetCursorPosition覆盖当前行输出进度,避免控制台刷屏,提升视觉体验 - 哈希算法切换:只需将
SHA256.Create()替换为SHA512.Create()即可切换到SHA512哈希计算 - 异常处理:针对文件读取失败、权限不足等常见异常做了捕获,保证程序不会因单个文件问题中断
- 性能优化:初始化
Dictionary时指定总文件数作为初始容量,减少内存扩容开销;使用using语句自动释放流和哈希算法资源 - 递归处理子目录:若需要处理子目录,将
Directory.GetFiles(targetDir)替换为Directory.GetFiles(targetDir, "*", SearchOption.AllDirectories)
内容的提问来源于stack exchange,提问作者Gloomstick
相关产品推荐
相关产品推荐

