我有这种情况:
DownloadLibrary.GetData(Stream targetStream);
SaveLibrary.WriteData(Stream sourceStream);
我想将targetStream收集的数据发送到sourceStream。我想出了一些解决方案,但我找不到直接连接这些流的方法。
我想要实现的是将数据从targetStream发送到sourceStream而不首先缓冲targetStream。
怎么做?
提前致谢。
答案 0 :(得分:6)
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.");
}
答案 1 :(得分:2)
chibacity答案中引用的内置CopyTo方法可从.NET 4.0获得。
对于早期版本,请查看this question。