title: How to create a stream wrapping stream that can transform a stream
body: <pre><code>var incomingStream = ...
  var outgoingStream = ...
  
  await incomingStream.CopyToAsync(outgoingStream);
  </code></pre>
  
  <p>The above code is simple enough, and copies a incoming stream to the outgoign stream. Both streams being chunked transfers coming/going over the interet.</p>
  
  <p>Now, lets say i wanted to Transform the stream with something like <code>Func&lt;Stream,Stream,Task&gt;</code> how would I do that without reading all data in.</p>
  
  <p>Ofcause I could just do</p>
  
  <pre><code>var ms = new MemoryStream();
  incomingStream.CopyTo(ms);
  
  --- do transform of streams and seek
  ms.CopyTo(outgoingStream)
  </code></pre>
  
  <p>but that would read the hole thing into the ms, is there any build in stuff that allows me to read from incoming stream and write to a new stream that dont buffer everything up but instead just keep a small internal stream for buffered data and it wont read from incoming stream before data is pulled off it again.</p>
  
  <p>What I am trying to do is:</p>
  
  <pre><code>    protected async Task XmlToJsonStream(Stream instream, Stream outStream)
      {
          XmlReaderSettings readerSettings = new XmlReaderSettings();
          readerSettings.IgnoreWhitespace = false;
          var reader = XmlReader.Create(instream, readerSettings);
          var jsonWriter = new JsonTextWriter(new StreamWriter(outStream));
          jsonWriter.WriteStartObject();
  
          while (await reader.ReadAsync())
          {
              jsonWriter.writeReader(reader);
          }
          jsonWriter.WriteEndObject();
          jsonWriter.Flush();
      }
      protected async Task XmlFilterStream(Stream instream, Stream outStream)
      {
          XmlReaderSettings readerSettings = new XmlReaderSettings();
          readerSettings.IgnoreWhitespace = false;
          var reader = XmlReader.Create(instream, readerSettings);
          var writer = XmlWriter.Create(outStream, new XmlWriterSettings { Async = true, CloseOutput = false })
  
          while (reader.Read())
          {
              writer.writeReader(reader);
          }
  
  
      }
  </code></pre>
  
  <p>but i dont know how to hook it up.</p>
  
  <pre><code>var incomingStream = ...
  var outgoingStream = ...
  var temp=...  
  XmlFilterStream(incomingStream,temp);
  XmlToJsonStream(temp,outgoingstream);
  </code></pre>
  
  <p>because if I use a MemoryStream as temp, would it not just at the end have it all stored in the stream. Looking for at stream that throws away the data again when it has been read.</p>
  
  <p>All of the above is just example code, missing some disposes and seeks ofcause, but I hope I managed to illustrate what i am going for. To be able to based on settings to plug and play between just copying stream, doing xml filtering and optional transform it to json.</p>