【发布时间】:2015-06-29 14:39:56
【问题描述】:
如果我可以就我遇到的问题寻求帮助,我想打开一个文件夹来显示每个文件及其哈希值,然后在显示文件的末尾我想要一个哈希值来显示总文件夹结构。下面的代码不正确,因为它将路径 MD5 添加到文件 MD5 中。
下面的代码在列表框中显示每个文件,并在其下方显示一个哈希,但哈希代码是每个文件刚刚重复的文件夹的哈希。
private void btnFolder_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
_path = folderBrowserDialog1.SelectedPath;
txtFolder.Text = _path;
// assuming you want to include nested folders
var files = Directory.GetFiles(_path, "*.*", SearchOption.TopDirectoryOnly)
.OrderBy(p => p).ToList();
foreach (string items in files)
{
MD5 md5 = MD5.Create();
for (int i = 0; i < files.Count; i++)
{
string file = files[i];
// hash path
string relativePath = file.Substring(_path.Length + 1);
byte[] pathBytes = Encoding.UTF8.GetBytes(relativePath.ToLower());
md5.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
// hash contents
byte[] contentBytes = File.ReadAllBytes(file);
if (i == files.Count - 1)
md5.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
else
md5.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
}
lstBox.Items.Add(items);
lstBox.Items.Add(BitConverter.ToString(md5.Hash).Replace("-", "").ToLower());
}
}
else
{
return;
}
}
提前感谢您的帮助。
【问题讨论】:
-
你为什么要遍历你的
files数组两次? (一次是foreach,一次是for int i。这就是为什么你每次都会得到一个总哈希值,因为你每次都在哈希所有文件