生成文件MD5 Hash On Button单击C#.NET

时间:2016-05-07 12:08:41

标签: c# .net visual-studio md5

我正在尝试生成MD5哈希文件。

基本上它应该如何运作。

我按下我的软件上的浏览按钮,浏览我想要的文件>我选择了要扫描的文件>它会将MD5哈希值显示给标签

这是我想要完成的一个直观的例子。

我的问题是,如何获取MD5哈希,我从未见过任何从文件中获取MD5哈希值的代码,所以我不知道应该如何完成它。

enter image description here

2 个答案:

答案 0 :(得分:1)

这最终有效!

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


}

答案 1 :(得分:0)

尝试使用Windows窗体并根据需要进行修改:

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

它的组合 Calculate MD5 checksum for a fileHow to convert an MD5 hash to a string and use it as a file name