Calculate hash for a file in C#

In this article, I will show you how to calculate the hash of a given file in C#. Before that let’s understand what is hash and why it is important.

A hash function is used to convert data to other data of fixed size

Here fixed size is important because the hash function generates the same length of the data for a single character or a terabyte file.
Hashing can be used in the following scenario.

  • Integrity
  • Information loss
  • Storing the user passwords
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Blog_CS
{
    class Program
    {
        private const string FileName = @"D:\output.txt";
        static void Main(string[] args)
        {
            string fileHash = GetHashOfFile(FileName);
            Console.WriteLine(fileHash);
        }

        private static string GetHashOfFile(string fileName)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                //Create HashAlgorithm (MD5,SHA1...)
                HashAlgorithm hash = HashAlgorithm.Create("MD5");
                byte[] hashByte = hash.ComputeHash(fileStream);
                return String.Join(",", hashByte);
            }
        }
    }
}

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم