繁体   English   中英

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

[英]Generate files MD5 Hash On Button Click C# .NET

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

基本上它应该如何工作。

我按下我的软件上的浏览按钮来浏览我想要扫描的文件 > 我选择我想要扫描的文件 > 并且它会显示一个标签的 MD5 哈希值

这是我试图完成的视觉示例。

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

在此处输入图片说明

这就是最终奏效的方法!

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


}

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

它结合了计算文件的 MD5 校验和和如何将 MD5 哈希转换为字符串并将其用作文件名

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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