【问题标题】:Reading stream in chunks fails - destination array not long enough分块读取流失败 - 目标数组不够长
【发布时间】:2014-05-11 02:05:56
【问题描述】:

我目前正在编写一些代码来处理和加密 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);
            }
        }
    }
}

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

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 和长度,以及数组的下限”错误。我阅读了有关填充的各种帖子,但即使将数据字节数组增加一倍大小仍然会出现错误。

我毫不怀疑我遗漏了一些明显的东西。有人可以帮忙吗?

谢谢,

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:
    int n = inputStream.Read(data, numBytesRead, byteBuffer);
    

    应该是

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

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

    【讨论】:

    • 很好看。然而,此外,“cs.write”行的偏移量也应该为零——但在这些更改之后它都起作用了。非常感谢,
    猜你喜欢
    • 2012-05-08
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2017-06-20
    • 2016-04-08
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多