我怎么一个流中的内容复制到另一个? [英] How do I copy the contents of one stream to another?

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

问题描述

什么是一个流中的内容复制到另一个的最佳方式?有没有一个标准的工具方法为这个?

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的,有<一个href=\"http://msdn.microsoft.com/en-us/library/system.io.stream.copytoasync.aspx\"><$c$c>Stream.CopyToAsync方法

From .NET 4.5 on, there is the Stream.CopyToAsync method

input.CopyToAsync(output);

这将返回一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx\"><$c$c>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 制成,在code后面可能会或可能不会继续调用它的同一线程上。

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.

的<一个href=\"http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx\"><$c$c>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,还有就是<一个href=\"http://msdn.microsoft.com/en-us/library/system.io.stream.copyto.aspx\"><$c$c>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);
    }
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆