Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert StreamReader to byte[]

Tags:

c#

stream

I am getting the result StreamReader object.

I want to convert the result into byte[].

How can I convert StreamReaderto byte[]?

Thanks

like image 464
usr021986 Avatar asked May 03 '11 08:05

usr021986


1 Answers

Just throw everything you read into a MemoryStream and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.

var bytes = default(byte[]); using (var memstream = new MemoryStream()) {     var buffer = new byte[512];     var bytesRead = default(int);     while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)         memstream.Write(buffer, 0, bytesRead);     bytes = memstream.ToArray(); } 

Or if you don't want to manage the buffers:

var bytes = default(byte[]); using (var memstream = new MemoryStream()) {     reader.BaseStream.CopyTo(memstream);     bytes = memstream.ToArray(); } 
like image 117
Jeff Mercado Avatar answered Oct 02 '22 17:10

Jeff Mercado