本文介绍了如何将一个流的内容复制到另一个流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将一个流的内容复制到另一个流的最佳方法是什么?有没有标准的实用方法?

What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?

推荐答案

从 .NET 4.5 开始,有 Stream.CopyToAsync 方法

input.CopyToAsync(output);

这将返回一个Task 完成后可以继续,如下所示:

This will return a Task that can be continued on when completed, like so:

await input.CopyToAsync(output)

// Code from here on will be run in a continuation.

请注意,根据调用 CopyToAsync 的位置,后面的代码可能会或可能不会在调用它的同一线程上继续.

Note that depending on where the call to CopyToAsync is made, the code that follows may or may not continue on the same thread that called it.

SynchronizationContext 调用 await 将决定将在哪个线程上执行延续.

The SynchronizationContext that was captured when calling await will determine what thread the continuation will be executed on.

此外,这个调用(这是一个可能会更改的实现细节)仍然对读取和写入进行排序(它只是不会浪费在 I/O 完成时阻塞的线程).

Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).

从 .NET 4.0 开始,有 Stream.CopyTo 方法

input.CopyTo(output);

对于 .NET 3.5 及之前版本

框架中没有任何东西可以帮助解决这个问题;您必须手动复制内容,如下所示:

There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

注意 1:此方法将允许您报告进度(到目前为止已读取 x 个字节...)
注意 2:为什么使用固定缓冲区大小而不是 input.Length?因为那个 Length 可能不可用!来自文档:

Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length? Because that Length may not be available! From the docs:

如果从 Stream 派生的类不支持查找,则调用 Length、SetLength、Position 和 Seek 会抛出 NotSupportedException.

这篇关于如何将一个流的内容复制到另一个流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:00