Skip to main content

The following example calculates the SHA-256 hash for all files in a directory.

using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;

namespace sha256Temp
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.Error.WriteLine("No directory specified.");
                Environment.Exit(1);
            }

            var directory = args[0];

            if (!Directory.Exists(directory))
            {
                Console.Error.WriteLine("The directory specified could not be found.");
                Environment.Exit(1);
            }

            // Create a DirectoryInfo object representing the specified directory.
            var directoryInfo = new DirectoryInfo(directory);

            // Get the FileInfo objects for every file in the directory.
            var files = directoryInfo.GetFiles();

            // Initialize a SHA256 hash object.
            using (var sha256 = SHA256.Create())
            {
                // Compute and print the hash values for each file in directory.
                foreach (var file in files)
                {
                    try
                    {
                        // Create a fileStream for the file.
                        var fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                        // Be sure it's positioned to the beginning of the stream.
                        fileStream.Position = 0;

                        // Compute the hash of the fileStream.
                        var hashValue = sha256.ComputeHash(fileStream);

                        // Write the name and hash value of the file to the console.
                        Console.Write($"{file.Name}: ");

                        PrintByteArray(hashValue);

                        // Close the file.
                        fileStream.Close();
                    }
                    catch (IOException e)
                    {
                        Console.Error.WriteLine($"I/O Exception: {e.Message}");
                        Environment.Exit(1);
                    }
                    catch (UnauthorizedAccessException e)
                    {
                        Console.Error.WriteLine($"Access Exception: {e.Message}");
                        Environment.Exit(1);
                    }
                }
            }
        }

        /// <summary>
        /// Display the byte bytes in a readable format.
        /// </summary>
        /// <param name="bytes"></param>
        private static void PrintByteArray(IReadOnlyList<byte> bytes)
        {
            for (var i = 0; i < bytes.Count; i++)
            {
                Console.Write($"{bytes[i]:X2}");

                // if (i % 4 == 3)
                // {
                //     Console.Write(" ");
                // }
            }

            Console.WriteLine();
        }
    }
}