互连流

发布于 2024-10-15 14:56:21 字数 304 浏览 5 评论 0原文

我有这样的场景:

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

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

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

怎么办呢?

提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

渡你暖光 2024-10-22 14:56:21

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

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.");
}
空名 2024-10-22 14:56:21

chibacity 的答案中提到的内置 CopyTo 方法可从 .NET 4.0 获得。

对于早期版本,请查看此问题

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

For earlier versions look at this question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文