System.IO.BufferedStream.Read 方法

方法描述

将字节从当前缓冲流复制到数组。

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

public override int Read(
	byte[] array,
	int offset,
	int count
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
array System-Byte[] 将字节复制到的缓冲区。
offset System-Int32 缓冲区中的字节偏移量,从此处开始读取字节。
count System-Int32 要读取的字节数。
返回值 System.Int32 读入 array 中的总字节数。 如果可用的字节没有所请求的那么多,总字节数可能小于请求的字节数;或者如果在可读取任何数据前就已到达流的末尾,则为零。

提示和注释

仅当到达流的末尾时,Read 方法才会返回零。 在所有其他情况中,Read 总是在返回前从流中读取至少一个字节。 根据定义,如果调用 Read 时流中没有数据可用,则 Read 方法返回零(自动到达流的末尾)。 即使尚未到达流的末尾,实现仍可以随意返回少于所请求的字节。

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

System.IO.BufferedStream.Read 方法例子

此代码示例摘自一个为 BufferedStream 类提供的更大的示例。

// Receive data using the BufferedStream.
Console.WriteLine("Receiving data using BufferedStream.");
bytesReceived = 0;
startTime = DateTime.Now;

int numBytesToRead = receivedData.Length;

while (numBytesToRead > 0)
{
    // Read may return anything from 0 to numBytesToRead.
    int n = bufStream.Read(receivedData,0, receivedData.Length);
    // The end of the file is reached.
    if (n == 0)
        break;
    bytesReceived += n;
    numBytesToRead -= n;
}

bufferedTime = (DateTime.Now - startTime).TotalSeconds;
Console.WriteLine("{0} bytes received in {1} seconds.\n",
    bytesReceived.ToString(),
    bufferedTime.ToString("F1"));

异常

异常 异常描述
ArgumentException array 的长度减去 offset 小于 count。
ArgumentNullException array 为 null。
ArgumentOutOfRangeException offset 或 count 为负。
IOException 流未打开或为 null。
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 系统要求。