简体   繁体   中英

Generate files MD5 Hash On Button Click C# .NET

I am trying to generate a files MD5 hash.

Essentially how it should work.

I press a browse button on my software to browse which file I want tos can > I select the file I want to scan > and it displays the MD5 hash to a label

here is a visual example of what I am trying to accomplish.

My question is, how do I grab the MD5 hash, I have never seen any code that grabs MD5 hashes from a file so I have no idea how its supposed to be done.

在此处输入图片说明

This is what worked in the end!

public string MD5HashFile(string fn)
{
    byte[] hash = MD5.Create().ComputeHash(File.ReadAllBytes(fn));
    return BitConverter.ToString(hash).Replace("-", "");

}

private void lblTitle_Load(object sender, EventArgs e)
{

}



private void scanButton_Click(object sender, EventArgs e)
{

    //Create a path to the textBox that holds the value of the file that is going to be scanned
    string path = txtFilePath.Text;

    //if there is something in the textbox to scan we need to make sure that its doing it.
    if (!File.Exists(path))
    {
                            // ... report problem to user.
      return;

    }
    else
    {
        MessageBox.Show("Scan Complete");
    }

    //Display the computed MD5 Hash in the path we declared earlier
    hashDisplay.Text = MD5HashFile(path);


}

Try this for windows forms and modify it for your needs:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        openFileDialog1.FileOk += OpenFileDialog1_FileOk;
    }

    private void OpenFileDialog1_FileOk(object sender, CancelEventArgs e)
    {
        string path = ((OpenFileDialog)sender).FileName;
        using (var md5 = MD5.Create())
        {
            using (var stream = File.OpenRead(path))
            {
                label1.Text = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "");
            }
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //show file dialog on form load
        openFileDialog1.ShowDialog();
    }
}

It's a combination of Calculate MD5 checksum for a file and How to convert an MD5 hash to a string and use it as a file name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM