我試圖做一個MD5哈希和在線教程的幫助下,我設法做出了一些有用的東西。但是,我無法弄清楚如何使代碼不僅僅是一個文件。C# - 如何在同一時間散列多個文件的MD5?
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string filePath = e.Argument.ToString();
byte[] buffer;
int bytesRead;
long size;
long totalBytesRead = 0;
using (Stream file = File.OpenRead(filePath))
{
size = file.Length;
using (HashAlgorithm hasher = MD5.Create())
{
do
{
buffer = new byte[4096];
bytesRead = file.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
hasher.TransformBlock(buffer, 0, bytesRead, null, 0);
backgroundWorker1.ReportProgress((int)((double)totalBytesRead/size * 100));
}
while (bytesRead != 0);
hasher.TransformFinalBlock(buffer, 0, 0);
e.Result = MakeHashString(hasher.Hash);
}
}
}
private static string MakeHashString(byte[] hashBytes)
{
StringBuilder hash = new StringBuilder(32);
foreach (byte b in hashBytes)
hash.Append(b.ToString("X2").ToLower());
return hash.ToString();
}
您的代碼只能設置爲一次處理一個文件,在這種情況下很好。在調用backgroundWorker1_DoWork()的方法中,它將循環遍歷所有文件,並分別爲每個文件調用worker方法。 – Taegost