What is the easiest way to obtain `byte[]` from `BlazorInputFile.IFileStream`

953 views Asked by At

I have a file that a user will select in their browser using BlazorInputFile as expounded by Steve Sanderson.

Once selected I want to calculate a checksum for the file using System.Security.Cryptography.MD5, similar to what's described in this answer to Calculate MD5 checksum for a file.

However, I encounter a System.NotSupportedException when I try this:

private string GetMd5ForFile(IFileListEntry file)
{
   using (var md5 = MD5.Create())
   {
      return Convert.ToBase64String(md5.ComputeHash(this.file.Data));
   }
}

Some exception details are:

 > Message: "Synchronous reads are not supported"
 > Source : "BlazorInputFile"
 > Stack  : "at BlazorInputFile.FileListEntryStream.Read(Byte[] buffer, Int32 offset, Int32 count)"

I know that ComputeHash() takes an array of byte. I've so far tried to cast BlazorInputFile's streams to familiar types or to read the bytes to an array with a method of its own FileStream, but without success.

1

There are 1 answers

2
Trevor Reid On BEST ANSWER

I ended up doing this:


private async Task<string> GetMd5ForFile(IFileListEntry file) {
    using (var md5 = MD5.Create()) {
        var data = await file.ReadAllAsync();
        return Convert.ToBase64String(md5.ComputeHash(data.ToArray()));
    }
}