C#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); 

然后我在File.Delete() ‘上得到’进程无法访问文件’exception。

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

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

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

导入名称空间

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

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

md5hasher.Clear()在你的循环之后可以做到这一点。

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

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