System.IO.Stream不包含CopyTo()的定义
本文关键字:定义 CopyTo 包含 IO Stream System | 更新日期: 2023-09-27 18:20:23
嗨,我收到错误"
"System.IO.Stream"不包含"CopyTo"的定义,并且没有扩展方法"CopyTo"接受类型为的第一个参数找不到"System.IO.Stream"(是否缺少using指令还是程序集引用?)
"我在我的项目中使用了以下几行代码。
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);
}
正如Caboosetp所提到的,我认为正确的方法(我从其他地方得到的,可能是在SO上)是:
public static void CopyTo(Stream input, Stream outputStream)
{
byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
}
}
带有:
Stream stream = MyService.Download(("1231"));
using (Stream s = File.Create(file_path))
{
CopyTo(stream, s);
}