36

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.

jorgehmv
  • 3,633
  • 3
  • 25
  • 39

2 Answers2

52

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;
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
12

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

Jace
  • 1,445
  • 9
  • 20
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 7
    Just to keep the page consistent: the _IternalCopyTo_ method described _Reads_ from current stream into buffer - reading starts from the current position of the stream (index and offset parameters are index and offset in the buffer) - that is the "remains mechanism" – Max Yakimets Jan 17 '14 at 07:40