Stream.CopyTo 方法

定义

从当前流中读取字节并将其写入到另一流中。 这两个流位置都按复制的字节数提前。

重载

CopyTo(Stream)

从当前流中读取字节并将其写入到另一流中。 这两个流位置都按复制的字节数提前。

CopyTo(Stream, Int32)

使用指定的缓冲区大小,从当前流中读取字节并将其写入到另一流中。 这两个流位置都按复制的字节数提前。

CopyTo(Stream)

Source:
Stream.cs
Source:
Stream.cs
Source:
Stream.cs

从当前流中读取字节并将其写入到另一流中。 这两个流位置都按复制的字节数提前。

C#
public void CopyTo (System.IO.Stream destination);

参数

destination
Stream

当前流的内容将复制到的流。

例外

destinationnull

当前流不支持读取。

- 或 -

destination 不支持写入。

在调用 CopyTo(Stream) 方法前当前流或 destination 已关闭。

出现 I/O 错误。

示例

以下示例将 的内容 FileStream 复制到 MemoryStream

C#
// Create the streams.
MemoryStream destination = new MemoryStream();

using (FileStream source = File.Open(@"c:\temp\data.dat",
    FileMode.Open))
{

    Console.WriteLine("Source length: {0}", source.Length.ToString());

    // Copy source to destination.
    source.CopyTo(destination);
}

Console.WriteLine("Destination length: {0}", destination.Length.ToString());

注解

复制从当前流中的当前位置开始,并且不会在复制操作完成后重置目标流的位置。

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

CopyTo(Stream, Int32)

Source:
Stream.cs
Source:
Stream.cs
Source:
Stream.cs

使用指定的缓冲区大小,从当前流中读取字节并将其写入到另一流中。 这两个流位置都按复制的字节数提前。

C#
public void CopyTo (System.IO.Stream destination, int bufferSize);
C#
public virtual void CopyTo (System.IO.Stream destination, int bufferSize);

参数

destination
Stream

当前流的内容将复制到的流。

bufferSize
Int32

缓冲区的大小。 此值必须大于零。 默认大小为 81920。

例外

destinationnull

bufferSize 为负数或零。

当前流不支持读取。

- 或 -

destination 不支持写入。

在调用 CopyTo(Stream) 方法前当前流或 destination 已关闭。

出现 I/O 错误。

注解

复制从当前流中的当前位置开始,并且不会在复制操作完成后重置目标流的位置。

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0