Billa
Billa

Reputation: 5266

Append byte[] to MemoryStream

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

Upvotes: 2

Views: 17906

Answers (3)

Marcelo Vega
Marcelo Vega

Reputation: 1

Maybe this is a simple solution, not the best but is easy

 List<byte> list = new List<byte>();
 list.AddRange(Encoding.UTF8.GetBytes("aaaaaaaaaaaaa"));
 list.AddRange(Encoding.UTF8.GetBytes("bbbbbbbbbbbbbbbbbb"));
 list.AddRange(Encoding.UTF8.GetBytes("cccccccc"));

 byte[] c = list.ToArray();

Upvotes: 0

Paul Turner
Paul Turner

Reputation: 39625

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.

Upvotes: 0

L.B
L.B

Reputation: 116118

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).

Upvotes: 8

Related Questions