0

What is the easiest way to wrap a forward-only non-seekable source Stream (with CanSeek being false, e.g. an incoming network response) into a Stream that supports seeking, but does only read the same bytes from the source once?

Does .NET Standard (C#) offer any implementation of Stream which can be used for this or do I have to write this functionality by myself? I can imagine an implementation of Stream which gets the source Stream at construction, reads from it and stores bytes that are read for the first time in a cache or buffer which is then used for each subsequent read of the same bytes.

I don't want to wait for the source Stream to be read completely before accessing the wrapped Stream (because it's very large). Therefore copying the source into a local buffer before accessing the buffer is not what I want.

mxscho
  • 1,990
  • 2
  • 16
  • 27
  • So you want a thread/Task to read into a stream and update it, while another thread can access it and seek it, all while being thread safe? – TheGeneral Apr 06 '18 at 01:24
  • "I don't want to wait for the source Stream to be read completely" leaves you with a problem. Is `StreamWrapper.Position=futurePos` a blocking call? What if the source stream has no `Length`, can you `Position` past the end? How will this work? – spender Apr 06 '18 at 01:25
  • Is BufferedStream part of .NET Standard? – Ron Beyer Apr 06 '18 at 01:29
  • @TheGeneral It does not have to be multi-threaded. The wrapping `Stream` can as well just read from the source `Stream` if it has not yet stored the bytes in its cache. So... – mxscho Apr 06 '18 at 01:29
  • @spender ... yes, I think the `StreamWrapper.Position` setter call should block and wait until the source `Stream` has read enough to determine if enough bytes are available. – mxscho Apr 06 '18 at 01:29
  • Otherwise, [this answer](https://stackoverflow.com/a/28036366/14357) might get you there.... – spender Apr 06 '18 at 01:29

0 Answers0