Domanda

The following can scan a directory, return all files within it and save that information to a .txt file, but how and where do I write the function to get the checksum of that file next to it?

Example: C:\Desktop\E01.txt | 32DC1515AFDB7DBBEE21363D590E5CEA

I would really appreciate any help with this.

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

        }
È stato utile?

Soluzione

I've put together some code, to help you up. You will need to do the same for any other hash algorthim you may need.

just paste the snippet below, then add this modification:

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

Here you go:

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

Note I copied the ToHex from here -> byte[] to hex string

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top