使用StreamReader和Readline()为文件生成MD5值

时间:2014-11-25 20:42:31

标签: c# md5 readline

确定。我的问题的不同方面已经在这个论坛上被多次询问和回答。但是,我不认为我曾经问过我对这个问题的特殊修改。所以,在这里。我试图为同一文本文件生成两个哈希值,以便在数据文件处理之前和处理之后比较数据文件。这一点精神错乱的目的是验证整个文件是否已被程序读取和处理。

我已经向自己证明,使用字节和数组将文件分成大块,然后使用MD5.TransformBlock将创建一个has值(该程序代码遍布整个Web)。而且,当我运行我的程序时,两个哈希值是相同的。但是,我正在使用StreamReader的readline()方法一次读取一行文本文件,这会产生不正确的哈希值。

伪代码是:

BufferedStream reader = OpenFile(file)
string initialMd5 = generateMd5FromBufferedStream(reader)

//Start from the beginning again
reader.setposition = 0
reader.DiscardBufferedData();

while((tmpLine = reader.readline()) != null ) {
    Byte() buffer = GetBytes(tmpLine);
    md5.TransformBlock(buffer, 0, buffer.length, 0)
}

md5.TransformFinal(buffer, 0, 0);
String finalMd5 = ConvertToString(md5.Hash());

有什么想法?我对如何解决问题的想法不足。

提前致谢!!

3 个答案:

答案 0 :(得分:0)

所以,我在原帖中注意到的原因是,使用readline创建哈希的原因是我可以在读取和处理文件时生成哈希。想法是,如果读取和处理文件后的哈希与原始哈希相同,那么我可以确信整个文件已经处理完毕。

我们遇到StreamReader.ReadLine()没有读取整个文件的情况。出于某种原因,它只是在文件中间切断。但行为是随机的。而且,更糟糕的是,没有错误提出! Supid .NET!

无论如何,我的问题的答案是,当readline方法将字节数组(即文件中的一行文本)转换为字符串时,它会从字节数组中添加和减去“stuff”以执行转换。因此,经过大量研究工作后,答案似乎是在使用StreamReader.ReadLine读取文件时无法生成准确的哈希值。

现在,如果有人想到为什么愚蠢的东西停止在中间读取文件....

答案 1 :(得分:0)

这是我们当前正在使用的。

用法:

using (StreamReader file = new StreamReader(filepath))
{
    // store checksum
    Checksum = file.BaseStream.ToMD5Hash(); 
    ....
}

扩展方法:

public static string ToMD5Hash(this System.IO.Stream stream)
{
    string hash = string.Empty;
    long position = stream.Position;

    // Initialize a hash object
    using (System.Security.Cryptography.MD5 myHasher = System.Security.Cryptography.MD5.Create())
    {
        // Be sure it's positioned to the beginning of the stream
        stream.Position = 0;

        // Compute the hash of the stream and convert to a string
        hash = myHasher.ComputeHash(stream).ByteArrayToString();
    }

    // reset location
    stream.Position = position;         

    return hash;
}

答案 2 :(得分:-1)

这不是发布问题的答案,但是检查文件的上次访问权限或修改日期以检测更改是不够的? .Net在System.IO命名空间中有一个FileInfo类,其中包含LastAccessTime和LastWriteTime的属性。