C#MD5散列器的例子 [英] C# MD5 hasher example
问题描述
编辑:我改名这为code按预期工作为例
I've retitled this to an example as the code works as expected.
我试图复制一个文件,得到一个MD5哈希值,然后删除该副本。我这样做是为了避免对原文件,另一个应用程序写入过程锁。但是,我越来越对我复制的文件锁定。
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);
我然后得到一个进程无法访问文件'关于 File.Delete异常()
。
我期望与使用
声明中,文件流将很好地关闭。我也曾尝试单独声明文件流,删除使用
,并把 fs.Close()
和 fs.Dispose()
读了。
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.
在此之后,我注释掉实际MD5计算,和code excutes,文件被删除,所以它看起来像它的东西做 ComputeHash(FS)
。
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)
.
推荐答案
我把你的code把它在一个控制台应用程序并没有错误运行它时,得到了哈希和测试文件是在结束时删除执行?我只是用.PDB从我的测试应用程序的文件。
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.
您运行的是什么版本的.NET的?
What version of .NET are you running?
我把code,我有一个在这里工作,如果你把这个在一个控制台应用程序在VS2008 .NET 3.5 SP1它不出差错运行(至少对我来说)。
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;
}
}
}
这篇关于C#MD5散列器的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!