C# MD5 哈希器示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/827527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:14:24  来源:igfitidea点击:

C# MD5 hasher example

c#hashmd5

提问by mattdwen

Edit:I've retitled this to an example as the code works as expected.

编辑:我已将其重新命名为示例,因为代码按预期工作。

I am trying to copy a file, get a MD5 hash, then delete the copy. I am doing this to avoid process locks on the original file, which another app writes to. However, I am getting a lock on the file I've copied.

我正在尝试复制文件,获取 MD5 哈希值,然后删除副本。我这样做是为了避免对另一个应用程序写入的原始文件进行进程锁定。但是,我锁定了我复制的文件。

File.Copy(pathSrc, pathDest, true);

String md5Result;
StringBuilder sb = new StringBuilder();
MD5 md5Hasher = MD5.Create();

using (FileStream fs = File.OpenRead(pathDest))
{
    foreach(Byte b in md5Hasher.ComputeHash(fs))
        sb.Append(b.ToString("x2").ToLower());
}

md5Result = sb.ToString();

File.Delete(pathDest);

I am then getting a 'process cannot access the file' exception on File.Delete()'.

然后我在File.Delete()'.

I would expect that with the usingstatement, the filestream would be closed nicely. I have also tried declaring the filestream separately, removing using, and putting fs.Close()and fs.Dispose()after the read.

我希望通过该using语句,文件流会很好地关闭。我也曾尝试单独声明文件流,清除using,并把fs.Close()fs.Dispose()读取后。

After this, I commented out the actually md5 computation, and the code excutes, with the file being deleted, so it looks like it's something to do with ComputeHash(fs).

在此之后,我注释掉了实际的 md5 计算,代码执行,文件被删除,所以看起来它与ComputeHash(fs).

采纳答案by Brian ONeil

I took your code put it in a console app and ran it with no errors, got the hash and the test file is deleted at the end of execution? I just used the .pdb from my test app as the file.

我把你的代码放在一个控制台应用程序中并没有错误地运行它,得到了哈希值并且在执行结束时删除了测试文件?我只是使用了我的测试应用程序中的 .pdb 作为文件。

What version of .NET are you running?

您运行的是什么版本的 .NET?

I am putting the code that I have that works here, and if you put this in a console app in VS2008 .NET 3.5 sp1 it runs with no errors (at least for me).

我把我有的代码放在这里,如果你把它放在 VS2008 .NET 3.5 sp1 的控制台应用程序中,它运行没有错误(至少对我来说)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace lockTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string hash = GetHash("lockTest.pdb");

            Console.WriteLine("Hash: {0}", hash);

            Console.ReadKey();
        }

        public static string GetHash(string pathSrc)
        {
            string pathDest = "copy_" + pathSrc;

            File.Copy(pathSrc, pathDest, true);

            String md5Result;
            StringBuilder sb = new StringBuilder();
            MD5 md5Hasher = MD5.Create();

            using (FileStream fs = File.OpenRead(pathDest))
            {
                foreach (Byte b in md5Hasher.ComputeHash(fs))
                    sb.Append(b.ToString("x2").ToLower());
            }

            md5Result = sb.ToString();

            File.Delete(pathDest);

            return md5Result;
        }
    }
}

回答by Moose

Did you try wrapping your MD5 object in a using() too? From the docs, MD5 is Disposable. That might make it let go of the file.

您是否也尝试将 MD5 对象包装在 using() 中?从文档中,MD5 是一次性的。这可能会让它放开文件。

回答by Jagd

Have you tried setting md5Hasher to null before deleting the file? It probably has a handle still attached to the FileStream (memory leak perhaps).

您是否尝试在删除文件之前将 md5Hasher 设置为 null?它可能有一个仍然附加到 FileStream 的句柄(可能是内存泄漏)。

回答by Factor Mystic

Why not open the file with FileShare.ReadWrite?

为什么不使用 FileShare.ReadWrite 打开文件?

回答by JP Alioto

md5hasher.Clear()after your loop might do the trick.

md5hasher.Clear()在你的循环之后可能会起作用

回答by Sharp Coders

Import the name space

导入命名空间

using System.Security.Cryptography;

Here is the function that returns you md5 hash code. You need to pass the string as parameter.

这是返回 md5 哈希码的函数。您需要将字符串作为参数传递。

public static string GetMd5Hash(string input)
{
        MD5 md5Hash = MD5.Create();
        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data 
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
}