Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 759
agnieszka Avatar asked Dec 17 '08 21:12

agnieszka


People also ask

How do I read a byte stream?

1. The read() method of ByteArrayInputStream class in Java is used to read the next byte of the ByteArrayInputStream. This read() method returns the byte that is read int the form of an integer and if the input stream is ended this method return -1. This method reads one byte at a time from the stream.

What is the difference between Stream and MemoryStream?

You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string. You would not use a Stream in and of itself, but rather use it for polymorphism, i.e. passing it to methods that can accept any implementation of Stream as an argument.

How do I reuse MemoryStream?

You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0. By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters.

What is MemoryStream used for?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.


2 Answers

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.

like image 119
Andrew Kennan Avatar answered Oct 02 '22 17:10

Andrew Kennan


You need to reset the file pointer.

imageStream.Seek( 0, SeekOrigin.Begin );

Otherwise you're reading from the end of the stream.

like image 27
Joel Lucsy Avatar answered Oct 02 '22 17:10

Joel Lucsy