Question

I am trying to read the byte[] for each file and adding it to MemoryStream. Below is the code which throws error. What I am missing in appending?

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();              
}

Error:

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

No correct solution

OTHER TIPS

startPosition is not offset to MemoryStream, instead to ba. Change it as

allFrameStream.Write(ba, 0, ba.Length); 

All byte arrays will be appended to allFrameStream

BTW: Don't use ba = allFrameStream.GetBuffer(); instead use ba = allFrameStream.ToArray(); (You actually don't want internal buffer of MemoryStream).

The MSDN documentation on Stream.Write might help clarify the problem.

Streams are modelled as a continuous sequence of bytes. Reading or writing to a stream moves your position in the stream by the number of bytes read or written.

The second argument to Write is the index in the source array at which to start copying bytes from. In your case this is 0, since you want to read from the start of the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top