-1

I need to calculate MD5 for a file.

private string GetMD5(string file)
{
  using var md5 = MD5.Create();
  using var stream = new StreamReader(file);
  return (BitConverter.ToString(md5.ComputeHash(stream.BaseStream)).Replace("-", string.Empty)).ToLower();
}

private string GetMD5_V2(string file)
{
  using var md5 = MD5.Create();
  using var stream = new StreamReader(file);
  **_ = stream.EndOfStream;**
  return (BitConverter.ToString(md5.ComputeHash(stream.BaseStream)).Replace("-", string.Empty)).ToLower();
}

test()
{
  var fichier = "myFile.txt";
  var md5_1 = GetMD5(fichier);
  var md5_2 = GetMD5_V2(fichier);
}

When I run this code md5_1 and md5_2 is different. I not understand why when I read the propertie stream.EndOfStream this change the result of stream.BaseStream?

seb
  • 1
  • 1
  • Just wondering, but if you use the [StreamReader(Stream, Boolean)](https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.-ctor?view=net-6.0#system-io-streamreader-ctor(system-io-stream-system-boolean)) overload with the second parameter set to false, does it create the same results? If you set `stream.BaseStream.Position = 0` after doing `_ = stream.EndOfStream`, does the second example in the question give the same result as the first? – Andrew Morton Sep 22 '22 at 19:47
  • Side note: for future questions consider if example you show does not look ridiculous like in this case. I understand that the code shown is [mre] and not related to the code you have to just show the problem, but creating StreamReader on a file only to access its `BaseStream` looks... unwise - you may want to pick something that makes more sense or at least explicitly clarify that code is purely an example. – Alexei Levenkov Sep 22 '22 at 20:22

1 Answers1

0

StreamReader.EndOfStream consumes some bytes from the underlying stream.

Source

Specifically, it will read enough bytes to fill its own internal buffer. Since your MD5 is operating on that underlying stream and not on the StreamReader, the bytes sitting in that buffer are no longer available to the MD5 calculation.

Matt Thomas
  • 5,279
  • 4
  • 27
  • 59