gpt4 book ai didi

c# - 文件哈希算法代码c#

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:11:18 25 4
gpt4 key购买 nike

我的应用程序的一部分有望对用户指定的文件进行哈希处理,但我仍坚持使用实际代码本身。请注意:

filepath512(.text) = 用户插入文件路径的文本框

fileout(.text) = 输出文本框

button21_click = "Hash/confirm"按钮用于启动哈希算法

当我运行应用程序并运行哈希算法时,没有任何反应(结果没有出现在输出文本框中)。几周前,我实际上用相同的代码(好吧,相同的结构)成功地执行了哈希算法,而且运行得非常好!我刚刚开始使用 C#,所以请原谅任何困惑的代码!

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

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar3.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
fileout512.Text = e.Result.ToString();
progressBar3.Value = 0;
}

private void button21_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync(filepath512.Text);
}

最佳答案

实际上,您的代码遗漏了很多健全性检查。首先,您应该使用 OpenFileDialog 而不是直接用户输入来指定路径。其次,进程启动后,您应该使用 File.Exists 方法确保文件存在...如果不存在,您应该返回适​​当的结果。

您的代码可能在某处抛出了异常。来自官方MSDN documentation :

If the operation completes successfully and its result is assigned in the DoWork event handler, you can access the result through the RunWorkerCompletedEventArgs.Result property.

[...]

Your RunWorkerCompleted event handler should always check the Error and Cancelled properties before accessing the Result property. If an exception was raised or if the operation was canceled, accessing the Result property raises an exception.

因此,使用事件参数的 Error 属性检查错误详细信息,以确保您的代码无异常地正确执行。如果是这种情况,您必须修复代码,以便散列不再失败。

关于c# - 文件哈希算法代码c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48611489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com