【问题标题】:Generate files MD5 Hash On Button Click C# .NET生成文件 MD5 Hash On 按钮单击 C# .NET
【发布时间】:2016-05-07 12:08:40
【问题描述】:

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

基本上它应该如何工作。

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

这是我想要完成的一个视觉示例。

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

【问题讨论】:

  • 你试过这个链接吗:stackoverflow.com/questions/10520048/…
  • 是的,我看到了那个,老实说它看起来很棒,但我不知道如何在我的软件中使用它。如果你知道我会怎么走,我会喜欢一个解释:-)
  • 你的解释是指“有人可以帮我编码吗?”,因为这个例子再清楚不过了。您只需从 OpenFileDialog 获取文件路径,该路径将从“浏览文件”单击事件中触发,一旦选择了文件,您将该路径传递给 ComputeHash 方法。

标签: c# .net visual-studio md5


【解决方案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);


}

【讨论】:

    【解决方案2】:

    在 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

    【讨论】:

    • 我将忽略该代码,看看我能做些什么来制作类似但又不同的东西!很快就会回来!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多