System.IO.Stream.Read 方法

方法描述

当在派生类中重写时,从当前流读取字节序列,并将此流中的位置提升读取的字节数。

语法定义(C# System.IO.Stream.Read 方法 的用法)

public abstract int Read(
	byte[] buffer,
	int offset,
	int count
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
buffer System-Byte[] 字节数组。此方法返回时,该缓冲区包含指定的字符数组,该数组的 offset 和 (offset + count -1) 之间的值由从当前源中读取的字节替换。
offset System-Int32 buffer 中的从零开始的字节偏移量,从此处开始存储从当前流中读取的数据。
count System-Int32 要从当前流中最多读取的字节数。
返回值 System.Int32 读入缓冲区中的总字节数。 如果当前可用的字节数没有请求的字节数那么多,则总字节数可能小于请求的字节数;如果已到达流的末尾,则为零 (0)。

提示和注释

使用 CanRead 属性可确定当前实例是否支持读取。

此方法的实现从当前流中读取最多的 count 个字节,并将它们存储在从 offset 开始的 buffer 中。 流中的当前位置提升已读取的字节数;但是,如果出现异常,流中的当前位置保持不变。 实现返回已读取的字节数。 如果没有任何可用的数据,实现将会阻止,直到至少有一个字节的数据可供读取。 仅当流中没有更多数据且预期不会有更多数据(如套接字已关闭或位于文件结尾)时,Read 才返回 0。 即使尚未到达流的末尾,实现仍可以随意返回少于所请求的字节。

将 BinaryReader 用于读取基元数据类型。

System.IO.Stream.Read 方法例子

下面的示例显示如何使用 Read 读取数据块。

using System;
using System.IO;

public class Block
{
    public static void Main()
    {
        Stream s = new MemoryStream();
        for (int i = 0; i < 100; i++)
        {
            s.WriteByte((byte)i);
        }
        s.Position = 0;

        // Now read s into a byte buffer.
        byte[] bytes = new byte[s.Length];
        int numBytesToRead = (int) s.Length;
        int numBytesRead = 0;
        while (numBytesToRead > 0)
        {
            // Read may return anything from 0 to 10.
            int n = s.Read(bytes, numBytesRead, 10);
            // The end of the file is reached.
            if (n == 0)
            {
                break;
            }
            numBytesRead += n;
            numBytesToRead -= n;
        }
        s.Close();
        // numBytesToRead should be 0 now, and numBytesRead should
        // equal 100.
        Console.WriteLine("number of bytes read: {0:d}", numBytesRead);
    }
}

异常

异常 异常描述
ArgumentException offset 与 count 的和大于缓冲区长度。
ArgumentNullException buffer 为 null。
ArgumentOutOfRangeException offset 或 count 为负。
IOException 发生 I/O 错误。
NotSupportedException 流不支持读取。
ObjectDisposedException 在流关闭后调用方法。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。