36

I found upload code and this code contains the Stream.CopyTo method.

Example:

  file.Stream.CopyTo(requestStream); // .NET Framework 4.0

How can I copy "file.Stream" to "requestStream"?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mennan
  • 4,451
  • 13
  • 54
  • 86
  • In .NET version prior to 4.0 you must write your own method to copy the stream: http://stackoverflow.com/questions/230128/best-way-to-copy-between-two-stream-instances-c – Ladislav Mrnka Apr 20 '11 at 13:14

1 Answers1

87

You can't, basically. It's only implemented in .NET 4. You can write a similar method yourself though... and even make it an extension method:

// Only useful before .NET 4
public static void CopyTo(this Stream input, Stream output)
{
    byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size
    int bytesRead;

    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 6
    For a moment there I thought there was some awesome C# extension method feature I hadn't seen before! – MattDavey Apr 20 '11 at 13:25
  • Yea you have to remove it :) Thx again – Mennan Apr 20 '11 at 14:42
  • Async stream copy method can be found in .NET 4.5 http://msdn.microsoft.com/en-us/library/system.io.stream.copytoasync.aspx Async copy implementation for .NET 4.0 and less: http://stackoverflow.com/questions/1540658/net-asynchronous-stream-read-write – Vasyl Boroviak Sep 09 '13 at 07:11
  • For `MemoryStream`, you will want to add `input.Position = 0` otherwise – Charles Chen May 05 '15 at 23:43
  • @JonSkeet I used your example, how the heck do i stop the infinite read in while() if the Stream is a NetworkStream without forcing it out with a timeout as workaround. After sending all data this code remains stuck in Read mode, tried to use checks bytes sent or anything but it won't even reach the checks, if's or other stuff. The while condition remains true for the last read which is stuck on infinite read – Rares Andrei Jun 28 '20 at 02:10
  • @RaresAndrei: Basically you shouldn't read something that reads "until the end of the stream" with a stream that doesn't have an end. You should think about what condition you want to check for to see whether or not you've reached a suitable stopping point - that will depend on your context. – Jon Skeet Jun 28 '20 at 05:49