[C#]把一个流的所有字节复制到另一个流

这篇博文主要记录在C#里把一个流(Stream)里的所有字节复制到另外一个流的几种方法。

  • DotNet 4.5里可以用inStream.CopyToAsync(outStream)
  • DotNet 4.0里可以用inStream.CopyToAsync(outStream)
  • Dotnet 3.5或者更低版本,只能自己写CopyStream方法

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

参考了http://stackoverflow.com/questions/230128/best-way-to-copy-between-two-stream-instances

Leave a Reply

Your email address will not be published. Required fields are marked *