MemoryStream.Read doesn't copy bytes to buffer - c#

agnieszka picture agnieszka · Dec 17, 2008 · Viewed 22.3k times · Source

I don't really get it and it's driving me nuts. i've these 4 lines:

Image img = Image.FromFile("F:\\Pulpit\\soa.bmp");
MemoryStream imageStream = new MemoryStream();
img.Save(imageStream, ImageFormat.Bmp);
byte[] contentBuffer = new byte[imageStream.Length];
imageStream.Read(contentBuffer, 0, contentBuffer.Length);

when debugging i can see the bytes values in imageStream. after imageStream.Read i check content of contentBuffer and i see only 255 values. i can't get why is it happening? there is nothing to do wrong in these few lines! if anyone could help me it would be greatly appreciated! thanks, agnieszka

Answer

Andrew Kennan picture Andrew Kennan · Dec 17, 2008

Try setting imageStream.Position to 0. When you write to the MemoryStream it moves the Position after the bytes you just wrote so if you try to read there's nothing there.