Calculate File Checksum Using C#

less than 1 minute read

Calculate file checksum using c#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
 
namespace CheckSumTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"G:\Mahedee_Share\Created\23062014-1\FileDeployManager\FileDeployManager\Form1.cs";
            
            string checksumMd5 = GetFileChecksum(filePath, Algorithms.MD5);
            string checksumSha1 = GetFileChecksum(filePath, Algorithms.SHA1);
            string checksumSha256 = GetFileChecksum(filePath, Algorithms.SHA256);
            string checksumSha384 = GetFileChecksum(filePath, Algorithms.SHA384);
            string checksumSha512 = GetFileChecksum(filePath, Algorithms.SHA512);
            string checksumRipemd160 = GetFileChecksum(filePath, Algorithms.RIPEMD160);
            Console.ReadKey();
          }
          
          public static string GetFileChecksum(string filePath, HashAlgorithm algorithm)
          {
            using (var stream = new BufferedStream(File.OpenRead(filePath), 100000))
            {
              byte[] hash = algorithm.ComputeHash(stream);
              return BitConverter.ToString(hash).Replace("-", String.Empty);
            }
          }
    
    }
    
    public static class Algorithms
    {
        public static readonly HashAlgorithm MD5 = new MD5CryptoServiceProvider();
        public static readonly HashAlgorithm SHA1 = new SHA1Managed();
        public static readonly HashAlgorithm SHA256 = new SHA256Managed();
        public static readonly HashAlgorithm SHA384 = new SHA384Managed();
        public static readonly HashAlgorithm SHA512 = new SHA512Managed();
        public static readonly HashAlgorithm RIPEMD160 = new RIPEMD160Managed();
    }
 
}

Comments