-3

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.

enter image description here

  • have you tried this link: http://stackoverflow.com/questions/10520048/calculate-md5-checksum-for-a-file – Robert May 07 '16 at 12:10
  • Yes, I saw that one, and to be honest it looked great but I have no idea how to use that for my software. If you know how I would go by I would love an explanation :-) – Alexander. Matt May 07 '16 at 12:12
  • 2
    And by explanation do you mean "can someone please code this for me?", because that example cannot be any clearer. You just have to get the file path from a, `OpenFileDialog`, which will be fired from the "Browse File" click event, and once a file has been selected, you pass that path to the `ComputeHash` method. – TEK May 07 '16 at 12:23

2 Answers2

1

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);


}
0

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

Community
  • 1
  • 1
Robert
  • 3,353
  • 4
  • 32
  • 50