title: How to copy a stream to another stream only when destination consumed
body: <p>Similar to <a href="https://stackoverflow.com/questions/230128/how-do-i-copy-the-contents-of-one-stream-to-another">How do I copy the contents of one stream to another?</a></p>
  
  <p>But my understanding of <code>sourceStream.CopyTo(destStream)</code> means it'll read the entire <code>sourceStream</code> 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 <em>O(2n)</em> rather than <em>O(n)</em>, right?  And if <code>destStream</code> is a temporary copy (i.e. <code>MemoryStream</code>), then I will also end up loading the entire source stream into memory for each copy.</p>
  
  <p>Is there a way to do it so that it's only copied as <code>destStream</code> is consumed/read? </p>
  
  <p>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 <code>FileStream</code>, so I'd rather not load the entire file into memory when I can rewind it and buffer it from the disk.</p>
  
  <p><strong>Example Scenario:</strong></p>
  
  <pre><code>void WriteToMany(Stream sourceStream, IEnumerable&lt;ICanPutStream&gt; destinations) {
      foreach(var endpoint in destinations) {
          // &lt;-- I need to make a copy of `stream` here because...
          endpoint.PutStream(sourceStream); // ...some endpoints automatically dispose the stream
      }
  }
  </code></pre>
  
  <p>If I make a copy before <code>PutStream</code> is called, it's going to read through the source stream.  I can live with that, but if I copy it to a <code>MemoryStream</code> it also loads it into memory <em>for each endpoint</em> (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 <code>PutStream</code> that the original stream gets copied/read.</p>