Interconnects

I have a scenario like this:

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

I want to send the data that targetStream collects to sourceStream. I came up with some solutions, but I cannot find a way to directly connect these streams.

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

How can I do that?

Thanks in advance.

+3
source share
2 answers

There is built-in support (from .Net 4.0) Streamfor copying one stream to another through CopyTo, for example:

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.");
}
+6
source

The built-in CopyTo method referenced in the chibacity response is available from .NET 4.0.

In earlier versions, see this question .

+2
source

Source: https://habr.com/ru/post/1789804/


All Articles