不支持同步读取 - 对于 Blazor 服务器输入流读取 (Blazorise)

问题描述 投票:0回答:1

在以下代码的

inputStream.Read(buffer)
中看到“不支持同步读取”错误:

public static void FileDecrypt(IFileEntry file, string newFileName, string key)
{
    FileStream fsCrypt = new(fileName, FileMode.Create);
    byte[] iv = new byte[16];
    using (Aes aes = Aes.Create())
    {
        aes.Key = Encoding.UTF8.GetBytes(key);
        aes.IV = iv;

        ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
        byte[] buffer = new byte[MAX_BYTES];
        int read;

        using Stream inputStream = file.OpenReadStream();
        try
        {
            // ********* Fails on this READ with Unsupported ******
            while ((read = inputStream.Read(buffer)) > 0)
            {
                byte[] result = decryptor.TransformFinalBlock(buffer, 0, read);
                fsCrypt.Write(result, 0, read);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

令人费解的是,

inputStream.Read(buffer)
适用于以下代码:

public static void FileEncrypt(IFileEntry file, string newFileName, string key)
{
    FileStream fsCrypt = new(fileName, FileMode.Create);
    byte[] iv = new byte[16];
    using (Aes aes = Aes.Create())
    {
        aes.Key = Encoding.UTF8.GetBytes(key);
        aes.IV = iv;

        ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
        // Write the results in 1 megabyte chunks
        byte[] buffer = new byte[MAX_BYTES];
        int read;

        using CryptoStream cryptoStream = new CryptoStream((Stream)fsCrypt, encryptor, CryptoStreamMode.Write);
        using Stream inputStream = file.OpenReadStream();
        try
        {
            // WORKS here!
            while ((read = inputStream.Read(buffer)) > 0)
            {
                cryptoStream.Write(buffer, 0, read);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

我确信这可能很简单,但我看不到。我正在使用

Blazorise
IFileEntry file
,但我也尝试了标准文件上传中的
IBrowserFile
构造,结果相同。尝试缓冲解密的输入,因为我认为文件大小可能会变大。 我也尝试了
ReadAsync()
方法,但它只是击中该线,然后再也没有返回。

c# stream blazor blazor-server-side blazorise
1个回答
0
投票

在 WebAssembly 上运行时,“不支持同步读取”错误是正确的。所有 I/O 都必须经过 JS Interop,而且始终是异步的。 每个异步操作都会抛出异常。

解决方法是使你的方法异步:

//static void FileDecrypt(IFileEntry file, string newFileName, string key)
  static async Task FileDecrypt(IFileEntry file, string newFileName, string key)

并执行所有 I/O 异步:

   // while ((read = inputStream.Read(buffer)) > 0)
      while ((read = await inputStream.ReadAsync(buffer)) > 0)
© www.soinside.com 2019 - 2024. All rights reserved.