Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it Possible to Clone a .NET Stream?

Tags:

c#

.net

Can we clone a Stream?

like image 384
sandhya Avatar asked Mar 22 '10 06:03

sandhya


1 Answers

No, streams usually refer to local resources of some kind (a socket, a file handle, etc) and so they can't be cloned or serialized. Furthermore many streams are forward-only and do not support seeking so you might not even be able to re-read from a stream.

What you can do from a readable stream though is copy it into a MemoryStream which can be moved around as a byte array.

See the following post for a code snippet showing how to do this: How do I copy the contents of one stream to another?

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);
    }
}
like image 193
Josh Avatar answered Oct 17 '22 01:10

Josh