我有这个场景:

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

我想将 targetStream 收集的数据发送到 sourceStream。我想出了一些解决方案,但我找不到直接连接这些流的方法。

我想要实现的是将数据从 targetStream 发送到 sourceStream 而不先缓冲 targetStream。

如何做呢?

提前致谢。

最佳答案

Stream 中有内置支持(来自 .Net 4.0),用于通过 CopyTo 将一个流复制到另一个流,例如:

stream1.CopyTo(stream2)

例子:
[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.");
}

关于c# - 互连流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4888802/

10-12 14:52