Similar to How do I copy the contents of one stream to another?
But my understanding of sourceStream.CopyTo(destStream)
means it'll read the entire sourceStream
from start to end (chunks or whatever) in order to copy it, and then the consumer goes back through and reads the stream again (its copy), resulting in O(2n) rather than O(n), right? And if destStream
is a temporary copy (i.e. MemoryStream
), then I will also end up loading the entire source stream into memory for each copy.
Is there a way to do it so that it's only copied as destStream
is consumed/read?
Specifically, in .NET C# I need to make a copy of an input stream and write it to multiple "destinations" (via various helper libraries, some of which dispose of the stream they're given). The input could be very large, and is usually actually a FileStream
, so I'd rather not load the entire file into memory when I can rewind it and buffer it from the disk.
Example Scenario:
void WriteToMany(Stream sourceStream, IEnumerable<ICanPutStream> destinations) {
foreach(var endpoint in destinations) {
// <-- I need to make a copy of `stream` here because...
endpoint.PutStream(sourceStream); // ...some endpoints automatically dispose the stream
}
}
If I make a copy before PutStream
is called, it's going to read through the source stream. I can live with that, but if I copy it to a MemoryStream
it also loads it into memory for each endpoint (with the added weirdness of trying to dispose of something that may/not be disposed already). Ideally it would only be during the internal workings of PutStream
that the original stream gets copied/read.