System.IO.FileStream.ReadByte 方法

方法描述

从文件中读取一个字节,并将读取位置提升一个字节。

语法定义(C# System.IO.FileStream.ReadByte 方法 的用法)

public override int ReadByte()

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
返回值 System.Int32 强制转换为 Int32 的字节;如果已到达流的末尾,则为 -1。

提示和注释

此方法重写 ReadByte。

注意

使用 CanRead 属性可确定当前实例是否支持读取。 有关更多信息,请参见CanRead。

对实现者的说明

Stream 的默认实现创建一个新的单字节数组,然后调用 Read。 虽然这样做形式上是正确的,但效率不高。 所有具有内部缓冲区的流都应重写此方法,并提供一个可以直接读取缓冲区的更为有效的版本,从而避免每次调用都要进行额外的数组分配。

有关通用 I/O 任务的列表,请参见通用 I/O 任务。

System.IO.FileStream.ReadByte 方法例子

下面的代码示例说明如何逐字节地向文件中写入数据,然后验证数据是否被正确写入。

using System;
using System.IO;

class FStream
{
    static void Main()
    {
        const string fileName = "Test#@@#.dat";

        // Create random data to write to the file.
        byte[] dataArray = new byte[100000];
        new Random().NextBytes(dataArray);

        using(FileStream  
            fileStream = new FileStream(fileName, FileMode.Create))
        {
            // Write the data to the file, byte by byte.
            for(int i = 0; i < dataArray.Length; i++)
            {
                fileStream.WriteByte(dataArray[i]);
            }

            // Set the stream position to the beginning of the file.
            fileStream.Seek(0, SeekOrigin.Begin);

            // Read and verify the data.
            for(int i = 0; i < fileStream.Length; i++)
            {
                if(dataArray[i] != fileStream.ReadByte())
                {
                    Console.WriteLine("Error writing data.");
                    return;
                }
            }
            Console.WriteLine("The data was written to {0} " +
                "and verified.", fileStream.Name);
        }
    }
}

异常

异常 异常描述
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 系统要求。