Implementation example of C getting the value of file MD5

  • 2021-11-14 06:41:22
  • OfStack

Preface

MD5 is a common encryption method, which is relatively stable, and it is also a way to check files. This paper introduces the method of using C # to obtain the value of MD5 files, which can be used directly and can be used to compare whether files are the same. Let's not say much below. Let's look at the sample code

The sample code is as follows:


/// <summary>
    ///  Get a file MD5 Value 
    /// </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, FileMode.Open);
        System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] retVal = md5.ComputeHash(file);
        file.Close();

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

Summarize

The above is all about C # getting the file MD5 value. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.


Related articles: