views:

17069

answers:

8

What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?

+56  A: 

Feel free to edit this community post to fix bugs or implement improvements.

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

From .NET 4.0, there's a Stream.CopyTo method:

input.CopyTo(output);
Nick
It looks correct to me. I usually use the "while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)" idiom, but this is certainly okay :)
Jon Skeet
This makes me want an IOUtils clone for .Net. Thanks anyway. +1
Henning
Note that this is not the fastest way to do it. In the provided code snippet, you have to wait for the Write to complete before a new block is read. When doing the Read and Write asynchronously this waiting will disappear. In some situation this will make the copy twice as fast. However it will make the code a lot more complicated so if speed is not an issue, keep it simple and use this simple loop.This question on StackOverflow has some code that illustrates the async Read/Write: http://stackoverflow.com/questions/1540658/net-asynchronous-stream-read-writeRegards,Sebastiaan
Sebastiaan Megens
A: 

Unfortunately, there is no really simple solution. You can try something like that:

Stream s1, s2;
byte[] buffer = new byte[4096];
int bytesRead = 0;
while (bytesRead = s1.Read(buffer, 0, buffer.Length) > 0) s2.Write(buffer, 0, bytesRead);
s1.Close(); s2.Close();

But the problem with that that different implementation of the Stream class might behave differently if there is nothing to read. A stream reading a file from a local harddrive will probably block until the read operaition has read enough data from the disk to fill the buffer and only return less data if it reaches the end of file. On the other hand, a stream reading from the network might return less data even though there are more data left to be received.

Always check the documentation of the specific stream class you are using before using a generic solution.

DrJokepu
The generic solution will work here - Nick's answer is a fine one. The buffer size is an arbitrary choice of course, but 32K sounds reasonable. I think Nick's solution is right not to close the streams though - leave that to the owner.
Jon Skeet
+1  A: 

The basic questions that differentiate implementations of "CopyStream" are:

  • size of the reading buffer
  • size of the writes
  • Can we use more than one thread (writing while we are reading).

The answers to these questions result in vastly different implementations of CopyStream and are dependent on what kind of streams you have and what you are trying to optimize. The "best" implementation would even need to know what specific hardware the streams were reading and writing to.

fryguybob
... or the best implementation could have overloads to allow you to specify the buffer size, write size, and whether threads are allowed?
MarkJ
A: 

There may be a way to do this more efficiently, depending on what kind of stream you're working with. If you can convert one or both of your streams to a MemoryStream, you can use the GetBuffer method to work directly with a byte array representing your data. This lets you use methods like Array.CopyTo, which abstract away all the issues raised by fryguybob. You can just trust .NET to know the optimal way to copy the data.

Coderer
A: 

if you want a procdure to copy a stream to other the one that nick posted is fine but it is missing the position reset, it should be

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    long TempPos = input.Position;
    while (true)    
    {
        int read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
    }
    input.Position = TempPos;// or you make Position = 0 to set it at the start
}

but if it is in runtime not using a procedure you shpuld use memory stream

Stream output = new MemoryStream();
byte[] buffer = new byte[32768]; // or you specify the size you want of your buffer
long TempPos = input.Position;
while (true)    
{
    int read = input.Read (buffer, 0, buffer.Length);
    if (read <= 0)
        return;
    output.Write (buffer, 0, read);
 }
    input.Position = TempPos;// or you make Position = 0 to set it at the start
Kronass
You shouldn't change the position of the input stream, because not all streams allow random access. In a network stream, for example, you cannot change position, only read and/or write.
Martinho Fernandes
+3  A: 

There is actually, a less heavy-handed way of doing a stream copy. Take note however, that this implies that you can store the entire file in memory. Don't try and use this if you are working with files that go into the hundreds of megabytes or more, without caution.

public static void CopyStream(Stream input, Stream output)
{
  using (StreamReader reader = new StreamReader(input))
  using (StreamWriter writer = new StreamWriter(output))
  {
    writer.Write(reader.ReadToEnd());
  }
}

NOTE: There may also be some issues concerning binary data and character encodings.

SmokingRope
The default constructor for StreamWriter creates a UTF8 stream without a BOM (http://msdn.microsoft.com/en-us/library/fysy0a4b.aspx) so there's no danger of encoding problems. Binary data almost certainly shouldn't be copied this way.
David Kemp
+10  A: 

I use the following extension methods. They have optimized overloads for when one stream is a MemoryStream.

    public static void CopyTo(this Stream src, Stream dest)
    {
        int size = (src.CanSeek) ? Math.Min((int)(src.Length - src.Position), 0x2000) : 0x2000;
        byte[] buffer = new byte[size];
        int n;
        do
        {
            n = src.Read(buffer, 0, buffer.Length);
            dest.Write(buffer, 0, n);
        } while (n != 0);           
    }

    public static void CopyTo(this MemoryStream src, Stream dest)
    {
        dest.Write(src.GetBuffer(), (int)src.Position, (int)(src.Length - src.Position));
    }

    public static void CopyTo(this Stream src, MemoryStream dest)
    {
        if (src.CanSeek)
        {
            int pos = (int)dest.Position;
            int length = (int)(src.Length - src.Position) + pos;
            dest.SetLength(length); 

            while(pos < length)                
                pos += src.Read(dest.GetBuffer(), pos, length - pos);
        }
        else
            src.CopyTo((Stream)dest);
    }
Eloff
+3  A: 

MemoryStream has .WriteTo(outstream);

and .NET 4.0 has .CopyTo on normal stream object.

Joshua