Possible to calculate MD5 (or other) hash with buffered reads?

后端 未结 5 1688
长情又很酷
长情又很酷 2020-11-27 03:37

I need to calculate checksums of quite large files (gigabytes). This can be accomplished using the following method:

    private byte[] calcHash(string file         


        
5条回答
  •  长情又很酷
    2020-11-27 04:23

    I've just had to do something similar, but wanted to read the file asynchronously. It's using TransformBlock and TransformFinalBlock and is giving me answers consistent with Azure, so I think it is correct!

    private static async Task CalculateMD5Async(string fullFileName)
    {
      var block = ArrayPool.Shared.Rent(8192);
      try
      {
         using (var md5 = MD5.Create())
         {
             using (var stream = new FileStream(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 8192, true))
             {
                int length;
                while ((length = await stream.ReadAsync(block, 0, block.Length).ConfigureAwait(false)) > 0)
                {
                   md5.TransformBlock(block, 0, length, null, 0);
                }
                md5.TransformFinalBlock(block, 0, 0);
             }
             var hash = md5.Hash;
             return Convert.ToBase64String(hash);
          }
       }
       finally
       {
          ArrayPool.Shared.Return(block);
       }
    }
    

提交回复
热议问题