c# - System.IO.Stream 不包含 CopyTo() 的定义

标签 c# asp.net image .net-2.0

嗨,我收到错误消息“

'System.IO.Stream' does not contain a definition for 'CopyTo' and no extension method 'CopyTo' accepting a first argument of type 'System.IO.Stream' could be found (are you missing a using directive or an assembly reference?)

" 我在我的项目中使用以下代码行。

Bitmap img;
 using (var ms = new MemoryStream())
 {
    fu.PostedFile.InputStream.CopyTo(ms);
    ms.Position = 0;
    img = new System.Drawing.Bitmap(ms);
 }

为什么我会收到这个错误?如何解决?
请帮助我...

最佳答案

Stream.CopyTo 是在 .NET 4 中引入的。由于您的目标是 .Net 2.0,因此它不可用。在内部,CopyTo 主要做这个(尽管有额外的错误处理)所以你可以只使用这个方法。为了方便起见,我将其作为扩展方法。

//it seems 81920 is the default size in CopyTo but this can be changed
public static void CopyTo(this Stream source, Stream destination, int bufferSize = 81920)
{
    byte[] array = new byte[bufferSize];
    int count;
    while ((count = source.Read(array, 0, array.Length)) != 0)
    {
       destination.Write(array, 0, count);
    }
}

所以你可以简单地做

using (var ms = new MemoryStream())
{       
    fu.PostedFile.InputStream.CopyTo(ms);
    ms.Position = 0;
    img = new System.Drawing.Bitmap(ms);
}

关于c# - System.IO.Stream 不包含 CopyTo() 的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17390729/

相关文章:

c# - 如何获取下一个星期日的日期?

c# - 验证对 XML 进行数字签名始终为 false

c# - 有没有实现类似于MSMQ(Microsoft Message Queuing)的消息队列的免费库?

c++ - 单击按钮查看图像。 qt

image - 使用 FFMPEG 创建多个视频帧的单个图像

c# - 在 C# 中使用 Linq 或 lambda 从数据库中的表中获取 X 个随机元素

c# - 尽早控制大文件上传请求

asp.net - ASP.NET MVC问题与表单例份验证部分的配置

asp.net - 在当前 HTTPContext 中生成新的 ASP.NET session

html - li 行图像旁边的图像