如何在C#中的列表框中显示文件的MD5和SHA-1校验和?

时间:2014-04-26 23:35:07

标签: c# listbox md5

以下内容可以扫描目录,返回其中的所有文件并将该信息保存到.txt文件中,但是如何以及在何处编写该函数以获取该文件旁边的校验和?

示例:C:\ Desktop \ E01.txt | 32DC1515AFDB7DBBEE21363D590E5CEA

我真的很感激任何帮助。

private void btnScan_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        if (fbd.ShowDialog() == DialogResult.OK)

            listBox1.Items.Clear();
        string[] files = Directory.GetFiles(fbd.SelectedPath);
        string[] dirs = Directory.GetDirectories(fbd.SelectedPath);

        foreach (string file in files)
        {
            listBox1.Items.Add(file);
        }
        {
            foreach (string dir in dirs)
            {
                listBox1.Items.Add(dir);
            }
        }

    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        var saveFile = new SaveFileDialog();
        saveFile.Filter = "Text (*.txt)|*.txt";
        if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            using (var sw = new StreamWriter(saveFile.FileName, false))
                foreach (var item in listBox1.Items)
                    sw.Write(item.ToString() + Environment.NewLine);
            MessageBox.Show("This file was successfully saved.");

        }

1 个答案:

答案 0 :(得分:1)

我已经整理了一些代码,以帮助你。您需要对您可能需要的任何其他哈希值进行相同的操作。

只需粘贴下面的代码段,然后添加此修改:

    foreach (string file in files)
    {
        listBox1.Items.Add(file + " | " + GetSHA1Hex(file));
    }

你走了:

 public static string GetSHA1Hex(string fileName)
    {
        string result = string.Empty;

        using (System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create("SHA1"))
        using (System.IO.FileStream fs = System.IO.File.Open(fileName, System.IO.FileMode.Open))
        {
            byte[] b = sha1.ComputeHash(fs);
            result = ToHex(b);
        }

        return result;
    }

    public static string[] HexTbl = Enumerable.Range(0, 256).Select(v => v.ToString("X2")).ToArray();
    public static string ToHex(IEnumerable<byte> array)
    {
        System.Text.StringBuilder s = new System.Text.StringBuilder();
        foreach (var v in array)
            s.Append(HexTbl[v]);
        return s.ToString();
    }

注意我从这里复制了ToHex - &gt; byte[] to hex string