1
我目前正在編寫一些代碼來處理和加密上傳的文件在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和長度,和陣列的低。邊界「錯誤。我讀了關於填充的各種帖子,但即使增加數據字節數組來增加大小仍然會導致錯誤。
我毫不懷疑我錯過了一些明顯的東西。誰能幫忙?
感謝,
斑點。此外,'cs.write'行也應該有一個零偏移量 - 但它在所有這些變化之後都可以工作。非常感謝, – Simon