c# - 将 byte[] 附加到 MemoryStream

标签 c# asp.net .net c#-4.0

我正在尝试读取每个文件的 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/

相关文章:

c# - 从分组 Linq 查询生成字符串

asp.net - .NET Web 服务客户端是否可以支持同一 Web 服务的多个不同版本?

javascript - 访问位于代码后面的变量时的 ASP.NET 编译错误

c# - 如何阻止 System.Uri 取消对 URL 的编码?

c# - Task.WhenAll() - 它会创建一个新线程吗?

c# - 循环创建 MS Word 内容控件

c# - 异步在异步 Controller mvc 4.0 中不起作用

c# - 在 Silverlight 3 中获取当前用户控件或任何 GUI 的屏幕截图

asp.net - asp.net 中 <%= %> 语法和 <%# %> 之间有什么区别?

c++ - 使用 GetFieldProps 获取类的属性值