System.IO.BinaryWriter.Write 方法 (Byte)

方法描述

将一个无符号字节写入当前流,并将流的位置提升 1 个字节。

语法定义(C# System.IO.BinaryWriter.Write 方法 (Byte) 的用法)

public virtual void Write(
	byte value
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
value System-Byte 要写入的无符号字节。
返回值 void

提示和注释

因为存在数据格式设置冲突,所以不建议对以下编码方式使用此方法:

UTF-7

ISO-2022-JP

ISCII

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

System.IO.BinaryWriter.Write 方法 (Byte)例子

下面的代码示例说明如何通过将内存用作备份来写入二进制数据,然后验证数据是否被正确写入。

using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i = 0;

        // Create random data to write to the stream.
        byte[] writeArray = new byte[1000];
        new Random().NextBytes(writeArray);

        BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
        BinaryReader binReader = 
            new BinaryReader(binWriter.BaseStream);

        try
        {
            // Write the data to the stream.
            Console.WriteLine("Writing the data.");
            for(i = 0; i < writeArray.Length; i++)
            {
                binWriter.Write(writeArray[i]);
            }

            // Set the stream position to the beginning of the stream.
            binReader.BaseStream.Position = 0;

            // Read and verify the data from the stream.
            for(i = 0; i < writeArray.Length; i++)
            {
                if(binReader.ReadByte() != writeArray[i])
                {
                    Console.WriteLine("Error writing the data.");
                    return;
                }
            }
            Console.WriteLine("The data was written and verified.");
        }

        // Catch the EndOfStreamException and write an error message.
        catch(EndOfStreamException e)
        {
            Console.WriteLine("Error writing the data.\n{0}",
                e.GetType().Name);
        }
    }
}

异常

异常 异常描述
IOException 发生 I/O 错误。
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 系统要求。