简体   繁体   English

文件哈希算法代码C#

[英]File hash algorithm code c#

Part of my application will hopefully be able to hash files which the user specifies, but I am stuck on the actual code itself. 我的应用程序的一部分有望能够对用户指定的文件进行哈希处理,但是我仍然停留在实际的代码本身上。 Note that: 注意:

filepath512(.text) = Textbox in which the user inserts the file path filepath512(.text) =用户在其中插入文件路径的文本框

fileout(.text) = Output textbox fileout(.text) =输出文本框

button21_click = "Hash/confirm" button used to start the hashing algorithm button21_click =“哈希/确认”按钮,用于启动哈希算法

When I run the application and run the hashing algorithm, nothing happens (the result does not appear in the Output textbox). 当我运行应用程序并运行哈希算法时,什么也没发生(结果未出现在“输出”文本框中)。 A few weeks ago, I actually successfully executed the hashing algorithm with the identical code (well, same structure) and it worked perfectly well! 几周前,我实际上使用相同的代码(很好,相同的结构)成功地执行了哈希算法,并且效果很好! I have just begun working with C#, so please excuse any messy code! 我刚刚开始使用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);
    }

Actually, your code misses a lot of sanity checks. 实际上,您的代码缺少很多健全性检查。 First of all, you should use OpenFileDialog instead of a direct user input for specifying a path. 首先,您应该使用OpenFileDialog而不是直接用户输入来指定路径。 Second, once the process starts, you should make sure the file exists using File.Exists method... if it doesn't, you should return an appropriate result. 其次,一旦过程开始,您应该使用File.Exists方法确保文件存在...如果不存在,则应返回适当的结果。

Probably, an exception is being thrown by your code, somewhere. 可能是您的代码在某处引发了异常。 From the official MSDN documentation : 从官方MSDN文档中

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. 如果操作成功完成,并且在DoWork事件处理程序中分配了结果,则可以通过RunWorkerCompletedEventArgs.Result属性访问结果。

[...] [...]

Your RunWorkerCompleted event handler should always check the Error and Cancelled properties before accessing the Result property. 您的RunWorkerCompleted事件处理程序应始终在访问Result属性之前检查Error和Canceled属性。 If an exception was raised or if the operation was canceled, accessing the Result property raises an exception. 如果引发异常或操作被取消,则访问Result属性将引发异常。

So check error details using the Error properties of the event arguments in order to make sure that your code was properly executed without exceptions. 因此,请使用事件参数的Error属性检查错误详细信息,以确保代码正确无误地执行。 If this is the case, you must fix the code so that the hashing doesn't fail anymore. 在这种情况下,您必须修复代码,以使哈希不再失败。

does the file exists? 该文件是否存在? you have to check whether the file exists always before trying to do operations. 您必须在执行操作之前检查文件是否始终存在。 debug the filepath and see whether it exist, and it has read permissions. 调试文件路径,查看它是否存在,并且具有读取权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM