Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get a all the files present in a directory with their hashes as a Dictionary in C#?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading