编辑:,我已经将它重新命名为一个示例,因为代码按预期工作。
我正在尝试复制一个文件,获取一个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语句,文件将很好地关闭。我还尝试分别声明filestream,删除using,并将fs.Close()和fs.Dispose()放在读取后。
在此之后,我注释掉了实际的md5计算,代码在文件被删除后执行,所以看起来它与ComputeHash(fs)有关。
发布于 2009-05-06 01:54:22
我把您的代码放在控制台应用程序中,没有错误地运行它,得到了哈希,测试文件在执行结束时被删除了?我只是使用测试应用程序中的.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;
}
}
}发布于 2012-12-10 17:39:55
导入名称空间
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();
}发布于 2009-05-06 00:28:28
您是否也尝试过将MD5对象封装在try ()中?从文档来看,MD5是可处理的。这可能会让它松开文件。
https://stackoverflow.com/questions/827527
复制相似问题