我目前正在编写一些代码来处理和加密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和长度,以及数组的下限”错误。我阅读了有关填充的各种帖子,但即使将数据字节数组增加到大小的两倍仍会产生错误。
毫无疑问,我错过了一些明显的东西。有人可以帮忙吗?
谢谢,
答案 0 :(得分:4)
int n = inputStream.Read(data, numBytesRead, byteBuffer);
应该是
int n = inputStream.Read(data, 0, byteBuffer);
因为您放在那里的数字是您正在读取的缓冲区的 ,而不是流的偏移量。