[英]Difference between Stream.CopyTo and MemoryStream.WriteTo
I have a HttpHandler returning an image through Response.OutputStream
. 我有一个HttpHandler通过
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. GetImage()
方法返回一个Stream
,它实际上是一个MemoryStream
实例,它返回0个字节到浏览器。 If i change GetImage()
method signature to return a MemoryStream
and use the following line of code: 如果我更改
GetImage()
方法签名以返回MemoryStream
并使用以下代码行:
_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. 那么在MemoryStream类中WriteTo和CopyTo之间的区别是什么,以及在
GetImage()
方法签名中使用Stream
类使其工作的推荐方法是什么。
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. WriteTo()
在复制数据之前将读取位置重置为零 - 另一方面, CopyTo()
将复制流中当前位置之后剩余的任何数据。 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;
According to reflector, this is the CopyTo() method definition: 根据反射器,这是CopyTo()方法定义:
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 ). 我没有看到任何“遗迹机制”在这里......它复制了从
this
到目的地(缓冲区大小的块)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.