需要帮助来计算C#中的MD5哈希

时间:2018-07-01 16:09:37

标签: c#

我目前正在尝试制作一个程序来计算文件的MD5哈希值, 但是,出现以下错误:

System.ArgumentNullException:'路径不能为null。 参数名称:路径'

到目前为止,这是我的代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Security.Cryptography;
    using System.Windows.Forms;

    namespace MD5Checker
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
        InitializeComponent();
    }

    private void btnOpenFileDialog_Click(object sender, EventArgs e)
    {
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            string fname = openFileDialog.FileName;
            string FILENAME = "@" + fname;
            txtFile.Text = FILENAME;
        }
    }
    public string FILENAME { get; set; }

    private void btnCalculateMD5_Click(object sender, EventArgs e)
    {
        string results = CalculateMD5(FILENAME);
        richTextBox1.Text = results;
    }

    static string CalculateMD5(string filename)
    {
        using (var md5 = MD5.Create())
        {
            using (var stream = File.OpenRead(filename))
            {
                byte[] hash = md5.ComputeHash(stream);
                return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
            }
        }
    }
}

}

1 个答案:

答案 0 :(得分:3)

问题在于您不是在更新类的属性,而是在更新局部变量。

private void btnOpenFileDialog_Click(object sender, EventArgs e)
{
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        string fname = openFileDialog.FileName;

        // this is FILENAME
        string FILENAME = "@" + fname;
        // here you use FILENAME instead of this.FILENAME
        txtFile.Text = FILENAME;
    }
}

// this is this.FILENAME
public string FILENAME { get; set; }

private void btnCalculateMD5_Click(object sender, EventArgs e)
{
    // uses this.FILENAME
    string results = CalculateMD5(FILENAME);
    richTextBox1.Text = results;
}

您可以删除变量,以便始终使用该属性。当您使用它时,可以开始遵循约定并将其设置为PascalCase,以便记住它是属性而不是变量。另外,无需在文件路径之前添加@

private void btnOpenFileDialog_Click(object sender, EventArgs e)
{
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        FileName = openFileDialog.FileName;
        txtFile.Text = FileName;
    }
}

// this is this.FileName
public string FileName { get; set; }

private void btnCalculateMD5_Click(object sender, EventArgs e)
{
    // uses this.FileName
    string results = CalculateMD5(FileName);
    richTextBox1.Text = results;
}