I have a directory countaining a lot of files (around 650 files) and i want to get all the files present in this directory with their hash (something like sha256 or sha512) in a Dictionary while seeing the percentage of the operation? Because I assume that it would take some time to hash them.
>Solution :
You may want to consider trying this approach; based on similar cases, it has shown promising results and could potentially resolve the issue you’re encountering.
public static async Task<Dictionary<string, string>> GetFilesAndHashesAsync(string pathToDirectory, IProgress<double>? progress = null)
{
var filesDictionary = new Dictionary<string, string>();
using (var sha = SHA256.Create())
{
if (!Directory.Exists(pathToDirectory))
{
throw new DirectoryNotFoundException($"Directory not found: {pathToDirectory}");
}
var files = Directory.EnumerateFiles(pathToDirectory).ToArray();
var totalFiles = files.Length;
double processedFiles = 0;
foreach (var file in files)
{
using (var fileStream = File.OpenRead(file))
{
var hashBytes = await sha.ComputeHashAsync(fileStream);
var hashString = BitConverter.ToString(hashBytes).Replace("-", string.Empty);
filesDictionary.Add(Path.GetFileName(file), hashString);
}
processedFiles++;
progress?.Report(processedFiles / totalFiles * 100);
}
}
return filesDictionary;
}