Sample md5 code of the file using c after downloading the software

  • 2020-06-23 01:44:52
  • OfStack

A lot of friends in the download file, will often find that the site offers MD5 check code, actually is the function of the MD5 code when you download files, take you downloaded file MD5 check code, and download site provides comparison, if completely 1, explain you download files no problem, if you don't 1 to check code, description and download your files in the process of make a mistake, or be an error in the file you download, is the consistency with the original file not anyway. And as long as the file is not a sample, MD5 code is certainly not a sample, this is not repeated, so how to get the file MD5 code? Using the C# code is explained below.


//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;
using System.IO;
namespace MD5FileForm
{
    public partial class MD5Form : Form
    {
        public MD5Form()
        {
            InitializeComponent();
        }
        private void btnGetMD5_Click(object sender, EventArgs e)
        {
            MD5 md5 = MD5.Create();
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            FileStream fs = new FileStream(ofd.FileName, FileMode.Open);
            byte[] bs = md5.ComputeHash(fs);
            // Access to the MD5 code 
            string md5Str = BitConverter.ToString(bs).Replace("-","");
            MessageBox.Show(string.Format("[{0}] the MD5 Code is: \n{1}",ofd.FileName,md5Str));
        }
    }
}

The second use example


using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Test
{
    public class MD5Code
    {
        /// <summary>
        ///  Retrievable MD5 code 
        /// </summary>
        /// <param name="fileName"> File name passed in (including path and suffix name) </param>
        /// <returns></returns>
        public string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
                MD5 md5 = new 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);
            }
        }
    }
}


Related articles: