Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Stream.CopyTo and MemoryStream.WriteTo

I have a HttpHandler returning an image through Response.OutputStream. I have the following code:

_imageProvider.GetImage().CopyTo(context.Response.OutputStream); 

GetImage() method returns a Stream which is actually a MemoryStream instance and it is returning 0 bytes to the browser. If i change GetImage() method signature to return a MemoryStream and use the following line of code:

_imageProvider.GetImage().WriteTo(context.Response.OutputStream); 

It works and the browser gets an image. So what is the difference between WriteTo and CopyTo in MemoryStream class, and what is the recommended way to make this works using Stream class in GetImage() method signature.

like image 509
jorgehmv Avatar asked May 18 '12 21:05

jorgehmv


People also ask

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.

What is stream copy?

CopyTo(Stream) Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied. CopyTo(Stream, Int32) Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.


2 Answers

WriteTo() is resetting the read position to zero before copying the data - CopyTo() on the other hand will copy whatever data remains after the current position in the stream. That means if you did not reset the position yourself, no data will be read at all.

Most likely you just miss the following in your first version:

memoryStream.Position = 0; 
like image 73
BrokenGlass Avatar answered Oct 08 '22 22:10

BrokenGlass


According to reflector, this is the CopyTo() method definition:

private void InternalCopyTo(Stream destination, int bufferSize) {     int num;     byte[] buffer = new byte[bufferSize];     while ((num = this.Read(buffer, 0, buffer.Length)) != 0)     {         destination.Write(buffer, 0, num);     } } 

I dont see any "remains mechanism" here... It copies everything from this to destination ( in blocks of buffer size ).

like image 31
Royi Namir Avatar answered Oct 08 '22 23:10

Royi Namir