Search code examples
c#.netiostream

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


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 and closed without impacting each other. These streams should each return the same binary data that the original stream would. No need to implement Position or Seek and such... Forward only.

I'd prefer if it didn't just copy the whole stream into memory and serve it up multiple times, which would be fairly simple enough to implement myself.

Is there anything out there that could do this?


Solution

  • Not out of the box.

    You'll need to buffer the data from the original stream in a FIFO manner, discarding only data which has been read by all "reader" streams.

    I'd use:

    • A "management" object holding some sort of queue of byte[] holding the chunks to be buffered and reading additional data from the source stream if required
    • Some "reader" instances which known where and on what buffer they are reading, and which request the next chunk from the "management" and notify it when they don't use a chunk anymore, so that it may be removed from the queue