计算哈希在保存文件? [英] Computing Hash while saving a file?
问题描述
我有一个的InputStream
,我想用它来计算哈希值,将文件保存到磁盘。我想知道如何有效地做到这一点。我应该用一些任务,这样做的同时,我要重复的流通到两个流,一个是在 saveFile的
方法,一个是 computeHash
的方法,或者我应该做点别的?
I have an inputStream
that I want to use to compute a hash and save the file to disk. I would like to know how to do that efficiently. Should I use some task to do that concurrently, should I duplicate the stream pass to two streams, one for the the saveFile
method and one for thecomputeHash
method, or should I do something else?
推荐答案
怎么样使用其上运行的散列算法块级?您可将块添加到哈希值(使用TransformBlock),随后写块流中的文件的foreach块
What about using a hash algorithms that operate on a block level? You can add the block to the hash (using the TransformBlock) and subsequently write the block to the file foreach block in the stream.
未经测试的粗糙的镜头:
Untested rough shot:
using System.IO;
using System.Security.Cryptography;
...
public byte[] HashedFileWrite(string filename, Stream input)
{
var hash_algorithm = MD5.Create();
using(var file = File.OpenWrite(filename))
{
byte[] buffer = new byte[4096];
int read = 0;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
hash_algorithm.TransformBlock(buffer, 0, read, null, 0);
file.Write(buffer, 0, read);
}
hash_algorithm.TransformFinalBlock(buffer, 0, read);
}
return hash_algorithm.Hash;
}
这篇关于计算哈希在保存文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!