How can I split (copy) a Stream in .NET?

后端 未结 7 2289
北荒
北荒 2020-12-03 11:59

Does anyone know where I can find a Stream splitter implementation?

I\'m looking to take a Stream, and obtain two separate streams that can be independently read a

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 12:18

    I do not think you will be able to find a generic implementation to do just that. A Stream is rather abstract, you don't know where the bytes are coming from. For instance you don't know if it will support seeking; and you don't know the relative cost of operations. (The Stream might be an abstraction of reading data from a remote server, or even off a backup tape !).

    If you are able to have a MemoryStream and store the contents once, you can create two separate streams using the same buffer; and they will behave as independent Streams but only use the memory once.

    Otherwise, I think you are best off by creating a wrapper class that stores the bytes read from one stream, until they are also read by the second stream. That would give you the desired forward-only behaviour - but in worst case, you might risk storing all of the bytes in memory, if the second Stream is not read until the first Stream has completed reading all content.

提交回复
热议问题