3

I have this scenario:

DownloadLibrary.GetData(Stream targetStream);
SaveLibrary.WriteData(Stream sourceStream);

I want to send the data that targetStream collects to the sourceStream. I've come up with some solutions but I cannot find a way to connect those streams directly.

What I'm trying to achieve is send the data from targetStream to sourceStream without buffer the targetStream first.

How can it be done?

Thanks in advance.

vtortola
  • 34,709
  • 29
  • 161
  • 263

2 Answers2

6

There is built in support (from .Net 4.0) in Stream for copying one stream to another via CopyTo, e.g.:

stream1.CopyTo(stream2)

Example:

[Test]
public void test()
{
    string inString = "bling";

    byte[] inBuffer = Encoding.ASCII.GetBytes(inString);

    Stream stream1 = new MemoryStream(inBuffer);
    Stream stream2 = new MemoryStream();

    //Copy stream 1 to stream 2
    stream1.CopyTo(stream2);

    byte[] outBuffer = new byte[inBuffer.Length];

    stream2.Position = 0;        
    stream2.Read(outBuffer, 0, outBuffer.Length);

    string outString = Encoding.ASCII.GetString(outBuffer);

    Assert.AreEqual(inString, outString, "inString equals outString.");
}
Tim Lloyd
  • 37,954
  • 10
  • 100
  • 130
2

The built-in CopyTo method referred to in chibacity's answer is available from .NET 4.0.

For earlier versions look at this question.

Community
  • 1
  • 1
Joe
  • 122,218
  • 32
  • 205
  • 338