我正在尝试读取每个文件的 byte[]
并将其添加到 MemoryStream。下面是抛出错误的代码。我在追加时缺少什么?
byte[] ba = null;
List<string> fileNames = new List<string>();
int startPosition = 0;
using (MemoryStream allFrameStream = new MemoryStream())
{
foreach (string jpegFileName in fileNames)
{
ba = GetFileAsPDF(jpegFileName);
allFrameStream.Write(ba, startPosition, ba.Length); //Error here
startPosition = ba.Length - 1;
}
allFrameStream.Position = 0;
ba = allFrameStream.GetBuffer();
Response.ClearContent();
Response.AppendHeader("content-length", ba.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(ba);
Response.End();
Response.Close();
}
错误:
Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection
最佳答案
startPosition
没有偏移到 MemoryStream,而是偏移到 ba
。改成
allFrameStream.Write(ba, 0, ba.Length);
所有字节数组将附加到allFrameStream
顺便说一句:不要使用 ba = allFrameStream.GetBuffer();
而是使用 ba = allFrameStream.ToArray();
(你实际上不需要 MemoryStream 的内部缓冲区)。
关于c# - 将 byte[] 附加到 MemoryStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22149031/