C# 在C中为多个使用者拆分文件流#
我需要计算许多大文件的MD5校验和。这方面的代码非常简单:C# 在C中为多个使用者拆分文件流#,c#,.net,md5,filestream,hashcode,C#,.net,Md5,Filestream,Hashcode,我需要计算许多大文件的MD5校验和。这方面的代码非常简单: System.IO.FileStream file = new System.IO.FileStream(strFullPath, FileMode.Open); fsFile.Seek(1000, SeekOrigin.Begin); //skip some chars if need be System.Security.Cryptography.MD5 md5 = new System.Security.Cryptograp
System.IO.FileStream file = new System.IO.FileStream(strFullPath, FileMode.Open);
fsFile.Seek(1000, SeekOrigin.Begin); //skip some chars if need be
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] arrBtMd5 = md5.ComputeHash(fsFile);
如果要执行以下操作之一,则问题开始出现:
- 为同一个文件(md5、sha1、crc32)计算多个哈希函数 还有什么不可以)
- 计算整个文件的MD5,并使用 跳过了某些标题行
您可以尝试并行运行哈希程序,这是一种罕见的情况,在这种情况下,1个磁盘上的并行I/O可能会工作。我同意Henk Holtermans的回答。你得自己做分割。但是,您可以做的是不使用单个ComputeHash调用计算完整的哈希,而是使用
TransformBlock
调用以字节块的形式进行计算
有了它,您可以自己实例化一个大小的缓冲区,并将其作为后续并行TransformBlock调用的参数
编辑:下面是一些执行此任务的代码
static void Hash2Md5inParallel()
{
string strFullPath = YourFilePathGoesHere;
byte[] Buffer = new Byte[1000]; //Instantiate Buffer to copy bytes.
byte[] DumpBuffer = new Byte[1000]; //Send output to bin.
System.Security.Cryptography.MD5 md5_1 = new System.Security.Cryptography.MD5CryptoServiceProvider();
System.Security.Cryptography.MD5 md5_2 = new System.Security.Cryptography.MD5CryptoServiceProvider();
System.IO.FileStream file = new System.IO.FileStream(strFullPath, FileMode.Open);
file.Seek(1000, SeekOrigin.Begin); //skip some chars if need be
int BytesToHash = 0;
do
{
BytesToHash = file.Read(Buffer, 0, 1000);
md5_1.TransformBlock(Buffer, 0, BytesToHash, DumpBuffer, 0);
//enter some code to skip some bytes for the other hash if you like...
md5_2.TransformBlock(Buffer, 0, BytesToHash, DumpBuffer, 0);
}
while (BytesToHash > 0); //Repeat until no more bytes.
//call TransformFinalBlock to finish hashing - empty block is enough
md5_1.TransformFinalBlock(new byte[0], 0, 0);
md5_2.TransformFinalBlock(new byte[0], 0, 0);
//Get both Hashs.
byte[] hash1 = md5_1.Hash;
byte[] hash2 = md5_2.Hash;
}