Stream.CopyTo和MemoryStream.WriteTo之间的区别 [英] Difference between Stream.CopyTo and MemoryStream.WriteTo

查看:536
本文介绍了Stream.CopyTo和MemoryStream.WriteTo之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

它有效,浏览器获取图像.那么MemoryStream类中的WriteTo和CopyTo有什么区别,以及使用GetImage()方法签名中的Stream类使该方法工作的推荐方法是什么.

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.

推荐答案

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

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;

这篇关于Stream.CopyTo和MemoryStream.WriteTo之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆