How to Get a file’s checksum using any hashing algorithm in C#
By FoxLearn 3/20/2025 2:51:27 AM 62
Calculate a file’s SHA256 checksum
Let’s say you want to calculate the checksum of a file using the SHA256 algorithm specifically.
To get the SHA256 checksum, you can use the System.Security.Cryptography.SHA256
class, as shown below:
public static string GetSHA256Checksum(string filename) { using (var sha256 = System.Security.Cryptography.SHA256.Create()) { using (var stream = System.IO.File.OpenRead(filename)) { var hash = sha256.ComputeHash(stream); return BitConverter.ToString(hash).Replace("-", ""); } } }
This method computes the SHA256 checksum, converts it to a hexadecimal string, and removes the dash characters, which is the common format for SHA256 hashes.
To use this method on a file:
static void Main(string[] args) { var checksum = GetSHA256Checksum(@"C:\Documents\example.txt"); Console.WriteLine(checksum); }
The output will display the file’s SHA256 checksum:
4A1A1B45C29B0418BB35E40DAA9A018586D0C4064D15D1454AC9788DA7B38F98
Calculate checksum using any hashing algorithm
To make your checksum calculation more flexible, you can use System.Security.Cryptography.HashAlgorithm.Create()
to generate the checksum using any of the available algorithms. This method works by passing the name of the desired hashing algorithm (like "SHA256", "MD5", etc.) to the factory method.
However, this approach is unsafe because any invalid algorithm name will return null
. It’s better to define a wrapper function that ensures only valid hashing algorithms are used.
Here’s a general-purpose GetChecksum()
method, which accepts an enum to specify the algorithm type:
public static class ChecksumHelper { public static string GetChecksum(HashingAlgorithms algorithmType, string filename) { using (var hasher = System.Security.Cryptography.HashAlgorithm.Create(algorithmType.ToString())) { using (var stream = System.IO.File.OpenRead(filename)) { var hash = hasher.ComputeHash(stream); return BitConverter.ToString(hash).Replace("-", ""); } } } } public enum HashingAlgorithms { MD5, SHA1, SHA256, SHA384, SHA512 }
This method generates a checksum based on the chosen algorithm, converts it to a hexadecimal string, and removes dashes.
To use this function:
static void Main(string[] args) { var checksum = ChecksumHelper.GetChecksum(HashingAlgorithms.SHA1, @"C:\Documents\example.txt"); Console.WriteLine(checksum); }
The output will display the file’s SHA1 checksum:
3E5D4C8F6B2C5A9DBBB9456FF90D5E062FCF9D19
This approach gives you the flexibility to calculate a checksum using any of the five hashing algorithms without modifying the core logic.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization