SoFunction
Updated on 2025-03-07

Implementation example of C# obtaining file MD5 value

Preface

MD5 is a common encryption method, relatively stable, and it is also a way to verify files. This article introduces to you the method of using C# to obtain the MD5 value of a file. It can be used directly to compare whether the files are the same. Let's not say much about it, let's take a look at the sample code

The sample code is as follows:

/// <summary>
    /// Get the MD5 value of the file    /// </summary>
    /// <param name="fileName">Absolute path of file</param>    /// <returns>MD5 value</returns>    public static string GetMD5HashFromFile(string fileName)
    {
      try
      {
        FileStream file = new FileStream(fileName, );
        .MD5 md5 = new .MD5CryptoServiceProvider();
        byte[] retVal = (file);
        ();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i &lt; ; i++)
        {
          (retVal[i].ToString("x2"));
        }
        return ();
      }
      catch (Exception ex)
      {
        throw new Exception("GetMD5HashFromFile() fail,error:" + );
      }
    }

Summarize

The above is all about obtaining the MD5 value of the file C#. I hope that the content of this article will be of some help to everyone's study or work. If you have any questions, you can leave a message to communicate.