I have the following code, which is reading a Stream to store the content of it as a string. Unfortunately after the StreamReader is not used anymore, the hash value of the Stream has changed. How is this possible? The Stream is readonly and thus can’t be changed.
string content;
string hash = Cryptography.CalculateSHA1Hash(stream); // 5B006E35CF1838871FDC1E3DF52B0CB5A8A97274
using (StreamReader reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
hash = Cryptography.CalculateSHA1Hash(stream); // DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
The SHA1 value
DA39A3EE5E6B4B0D3255BFEF95601890AFD80709is the result of hashing an empty string. The call toCryptography.CalculateSHA1Hashreads everything (from the current position to the end) from the string and hashes it. There’s no more data to read after the first call toCryptography.CalculateSHA1Hash.I would also guess that your
StreamReader.ReadToEnd()returns an empty string due to the same reason.