C#MD5是一个例子

mat*_*wen 12 c# hash md5

编辑:我已经重新编写了一个示例,因为代码按预期工作.

我正在尝试复制文件,获取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);
Run Code Online (Sandbox Code Playgroud)

然后我得到一个'进程无法访问文件'的例外File.Delete()'.

我希望通过using声明,文件流可以很好地关闭.我还尝试单独声明文件流,删除using,放置fs.Close()fs.Dispose()读取后.

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

小智 20

导入名称空间

using System.Security.Cryptography;
Run Code Online (Sandbox Code Playgroud)

这是返回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();
}
Run Code Online (Sandbox Code Playgroud)


Bri*_*eil 15

我把你的代码放在一个控制台应用程序中并运行它没有错误,得到哈希并在执行结束时删除测试文件?我只是使用我的测试应用程序中的.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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)