c# - 分块读取流失败 - 目标数组不够长

标签 c# asp.net

我目前正在编写一些代码来在 ASP 中处理和加密上传的文件。我的第一次尝试有效(即使是大文件),但在服务器端处理需要一段时间。我相信这是因为我正在逐字节执行此操作。这是工作代码...

using (RijndaelManaged rm = new RijndaelManaged())
{
    using (FileStream fs = new FileStream(outputFile, FileMode.Create))
    {
        using (ICryptoTransform encryptor = rm.CreateEncryptor(drfObject.DocumentKey, drfObject.DocumentIV))
        {
            using (CryptoStream cs = new CryptoStream(fs, encryptor, CryptoStreamMode.Write))
            {
                int data;
                while ((data = inputStream.ReadByte()) != -1)
                    cs.WriteByte((byte)data);
            }
        }
    }
}

如前所述,上面的代码工作正常,但在服务器端处理时速度很慢。所以我想我会尝试读取 block 中的字节以加快速度(不知道这是否会/应该有所作为)。我试过这段代码...

int bytesToRead = (int)inputStream.Length;
int numBytesRead = 0;
int byteBuffer = 8192;

using (RijndaelManaged rm = new RijndaelManaged())
{
    using (FileStream fs = new FileStream(outputFile, FileMode.Create))
    {
        using (ICryptoTransform encryptor = rm.CreateEncryptor(drfObject.DocumentKey, drfObject.DocumentIV))
        {
            using (CryptoStream cs = new CryptoStream(fs, encryptor, CryptoStreamMode.Write))
            {
                do
                {
                    byte[] data = new byte[byteBuffer];

                    // This line throws 'Destination array was not long enough. Check destIndex and length, and the array's lower bounds.'
                    int n = inputStream.Read(data, numBytesRead, byteBuffer);

                    cs.Write(data, numBytesRead, n);

                    numBytesRead += n;
                    bytesToRead -= n;

                } while (bytesToRead > 0);
            }
        }
    }
}

但是,如代码所示 - 当我现在上传大文件时,出现“目标数组不够长。检查 destIndex 和长度,以及数组的下限”错误。我阅读了各种关于填充的帖子,但即使将数据字节数组增加一倍大小仍然会出现错误。

毫无疑问,我遗漏了一些明显的东西。谁能帮忙?

谢谢,

最佳答案

int n = inputStream.Read(data, numBytesRead, byteBuffer);

应该是

int n = inputStream.Read(data, 0, byteBuffer);

因为你放在那里的数字是你正在读取的缓冲区的偏移量,而不是流的偏移量。

关于c# - 分块读取流失败 - 目标数组不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22766578/

相关文章:

javascript - 在 Javascript 中获取 session 值?

asp.net - 在简单明了的 HTML5 选择元素中发出警告

c# - Log4net SmtpAppender 不工作

c# - 尝试使用 Graph API 访问驱动器项目时出现 "Tenant does not have a SPO license"

c# - Kinect NullReferenceException 错误

c# - 类型参数的约束 : interface vs. 抽象类

c# - 有没有办法做到这一点,在 List<T>.ForEach() 语句中分配一个值?

c# - Asp.net 验证。只允许用户在文本框中输入特定数字

c# - vb.net 相当于 "private void (string text)"

c# - 使用 OnValidateIdentity 对 cookie 数据执行额外的验证