Aru*_*ran 2 c# asp.net image .net-2.0
您好,我收到错误“
“System.IO.Stream”不包含“CopyTo”的定义,并且找不到接受“System.IO.Stream”类型的第一个参数的扩展方法“CopyTo”(您是否缺少 using 指令或程序集引用?)
“我在我的项目中使用以下代码行。
Bitmap img;
using (var ms = new MemoryStream())
{
fu.PostedFile.InputStream.CopyTo(ms);
ms.Position = 0;
img = new System.Drawing.Bitmap(ms);
}
Run Code Online (Sandbox Code Playgroud)
为什么我会收到此错误?怎么解决这个问题呢?
请帮我...
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);
}
}
Run Code Online (Sandbox Code Playgroud)
所以你可以简单地做
using (var ms = new MemoryStream())
{
fu.PostedFile.InputStream.CopyTo(ms);
ms.Position = 0;
img = new System.Drawing.Bitmap(ms);
}
Run Code Online (Sandbox Code Playgroud)