C# MD5 哈希器示例

发布于 2024-07-18 04:51:52 字数 779 浏览 6 评论 0原文

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

我正在尝试复制文件,获取 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);

然后我在 File.Delete() 上收到“进程无法访问文件”异常。

我希望使用 using 语句可以很好地关闭文件流。 我还尝试单独声明文件流,删除 using,并将 fs.Close()fs.Dispose() 放在读取之后。

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

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.

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()'.

I would expect that with the using statement, 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.

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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

柒夜笙歌凉 2024-07-25 04:51:52

导入名称空间

using System.Security.Cryptography;

这是返回 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();
}

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.

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();
}
淡莣 2024-07-25 04:51:52

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

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

我将可用的代码放在这里,如果您将其放入 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;
        }
    }
}

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.

What version of .NET are you running?

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).

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;
        }
    }
}
若有似无的小暗淡 2024-07-25 04:51:52

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

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.

清风夜微凉 2024-07-25 04:51:52

md5hasher.Clear() 之后你的循环可能会成功。

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

夏尔 2024-07-25 04:51:52

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

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

℉服软 2024-07-25 04:51:52

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

Why not open the file with FileShare.ReadWrite?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文