Stream.CopyTo 和 MemoryStream.WriteTo 之间的区别

本文关键字:之间 区别 WriteTo MemoryStream CopyTo Stream | 更新日期: 2023-09-27 18:34:41

我有一个通过Response.OutputStream返回图像的HttpHandler。我有以下代码:

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

GetImage()方法返回一个Stream,该实际上是一个MemoryStream实例,它向浏览器返回 0 个字节。如果我更改GetImage()方法签名以返回MemoryStream并使用以下代码行:

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

它可以工作,浏览器会得到一个图像。那么 MemoryStream 类中的 WriteTo 和 CopyTo 有什么区别,以及使用GetImage()方法签名中的类Stream推荐的方法是什么。

Stream.CopyTo 和 MemoryStream.WriteTo 之间的区别

WriteTo()在复制数据之前将读取位置重置为零 - 另一方面CopyTo()将复制流中当前位置之后剩余的任何数据。这意味着如果您没有自己重置仓位,则根本不会读取任何数据。

很可能您只是在第一个版本中错过了以下内容:

memoryStream.Position = 0;

根据反射器,这是 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);
    }
}

我在这里没有看到任何"遗骸机制"......它将所有内容从this复制到目标(以缓冲区大小的块为单位(。