Hi I am getting the error "

'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?)

" I am using following lines of code in my project.

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

Why I am getting this error? How to solve this?
Please help me...

有帮助吗?

解决方案

Stream.CopyTo was introduced in .NET 4. Since you're targeting .Net 2.0, it's not available. Internally, CopyTo is mainly doing this (although has extra error handling) so you can just use this method. I've made it an extension method for convenience.

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

So you can simply do

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

其他提示

As Caboosetp mentioned, I think the correct method, (which I got from somewhere else, probably on SO) is:

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

with:

Stream stream = MyService.Download(("1231"));
using (Stream s = File.Create(file_path))
{
    CopyTo(stream, s);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top