从`BlazorInputFile.IFileStream`获取`byte []`的最简单方法是什么

时间:2020-06-25 15:50:32

标签: c# .net md5 blazor blazorinputfile

我有一个文件,用户可以使用BlazorInputFileSteve Sanderson的浏览器中进行选择。

选择后,我想使用System.Security.Cryptography.MD5计算文件的校验和,类似于对 Calculate MD5 checksum for a file 的回答中所述。

但是,当我尝试这样做时,我遇到了System.NotSupportedException

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

一些例外的详细信息是:

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

我知道ComputeHash()采用byte的数组。到目前为止,我一直试图将BlazorInputFile的流转换为熟悉的类型,或者使用自己的FileStream方法将字节读取到数组中,但是没有成功。

1 个答案:

答案 0 :(得分:1)

我最终这样做了:


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