Search code examples
c#hashmd5filestream

MD5 to hash generating the same hash code


I'm setting up a Blob, and I need to get some stuff to insert them in my database, so I made a code to get an hashId based on my Stream

I have already tried to use IFormFile at me FileStorageService, but this is a little bit wrong.

private string GetMD5HashFromFile(Stream data)
       {
          using (var md5 = MD5.Create())
          {
            using (var fileStream = data)
              {

                  var hash = md5.ComputeHash(fileStream);

                  var hashString = Convert.ToBase64String(hash);

                  return hashString.TrimEnd('=');

              }

          }
       }

This code is always generating the same hash, and in this way, I can't save my Blob information on my database


Solution

  • Based on C.Evenhuis comment, a friend of mine resolve in this way:

     private string GetMD5HashFromFile(Stream data)
            {
                using (var md5 = MD5.Create())
                {
                    data.Position = 0;
                    var hash = md5.ComputeHash(data);
                    var hashString = Convert.ToBase64String(hash);
    
                    return hashString.TrimEnd('=');
    
                }
            }