开发者

Is it Possible to Clone a .NET Stream?

开发者 https://www.devze.com 2022-12-23 22:28 出处:网络
开发者_Python百科Can we clone a Stream?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

开发者_Python百科Can we clone a Stream?


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


No. Cloning is not a generally supported operation on the Stream class. To be so it would have to encompass all possible implementations of the Stream class.

This may be doable for items like a FileStream but consider what this would mean for say a NetworkStream. Cloning generally has the concept of creating completely separate objects which are identical at the point of creation. This is not generally doable on items like TCP connections which are typically wrapped in a NetworkStream at some level.


No, you can't clone a generic stream.


Not sure if you want to clone the stream before or after it has been consumed. This might be of some help if you need to duplicate the stream for other purposes. I needed to access the contents of a closed stream and this allowed me to copy the original stream contents to another stream. Accessing a closed stream.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号