System.IO.BinaryWriter 类

方法描述

以二进制形式将基元类型写入流,并支持用特定的编码写入字符串。

语法定义(C# System.IO.BinaryWriter 类 的用法)

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class BinaryWriter : IDisposable

构造函数

构造函数名称 构造函数描述
BinaryWriter() 初始化向流中写入的 BinaryWriter 类的新实例。
BinaryWriter(Stream) 基于所提供的流,用 UTF-8 作为字符串编码来初始化 BinaryWriter 类的新实例。
BinaryWriter(Stream, Encoding) 基于所提供的流和特定的字符编码,初始化 BinaryWriter 类的新实例。

成员/方法

方法名称 方法描述
Close 关闭当前的 BinaryWriter 和基础流。
Dispose() 释放由 BinaryWriter 类的当前实例占用的所有资源。
Dispose(Boolean) 释放由 BinaryWriter 占用的非托管资源,还可以另外再释放托管资源。
Equals(Object) 确定指定的 Object 是否等于当前的 Object。 (继承自 Object。)
Finalize 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
Flush 清理当前编写器的所有缓冲区,使所有缓冲数据写入基础设备。
GetHashCode 用作特定类型的哈希函数。 (继承自 Object。)
GetType 获取当前实例的 Type。 (继承自 Object。)
MemberwiseClone 创建当前 Object 的浅表副本。 (继承自 Object。)
Seek 设置当前流中的位置。
ToString 返回表示当前对象的字符串。 (继承自 Object。)
Write(Boolean) 将单字节 Boolean 值写入当前流,其中 0 表示 false,1 表示 true。
Write(Byte) 将一个无符号字节写入当前流,并将流的位置提升 1 个字节。
Write(Byte[]) 将字节数组写入基础流。
Write(Char) 将 Unicode 字符写入当前流,并根据所使用的 Encoding 和向流中写入的特定字符,提升流的当前位置。
Write(Char[]) 将字符数组写入当前流,并根据所使用的 Encoding 和向流中写入的特定字符,提升流的当前位置。
Write(Decimal) 将一个十进制值写入当前流,并将流位置提升十六个字节。
Write(Double) 将 8 字节浮点值写入当前流,并将流的位置提升 8 个字节。
Write(Int16) 将 2 字节带符号整数写入当前流,并将流的位置提升 2 个字节。
Write(Int32) 将 4 字节带符号整数写入当前流,并将流的位置提升 4 个字节。
Write(Int64) 将 8 字节带符号整数写入当前流,并将流的位置提升 8 个字节。
Write(SByte) 将一个有符号字节写入当前流,并将流的位置提升 1 个字节。
Write(Single) 将 4 字节浮点值写入当前流,并将流的位置提升 4 个字节。
Write(String) 将有长度前缀的字符串按 BinaryWriter 的当前编码写入此流,并根据所使用的编码和写入流的特定字符,提升流的当前位置。
Write(UInt16) 将 2 字节无符号整数写入当前流,并将流的位置提升 2 个字节。
Write(UInt32) 将 4 字节无符号整数写入当前流,并将流的位置提升 4 个字节。
Write(UInt64) 将 8 字节无符号整数写入当前流,并将流的位置提升 8 个字节。
Write(Byte[], Int32, Int32) 将字节数组部分写入当前流。
Write(Char[], Int32, Int32) 将字符数组部分写入当前流,并根据所使用的 Encoding(可能还根据向流中写入的特定字符),提升流的当前位置。
Write7BitEncodedInt 以压缩格式写出 32 位整数。

提示和注释

派生类可重写该类的方法,以提供唯一的字符编码。

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

System.IO.BinaryWriter 类例子

下面的代码示例阐释了如何在文件中存储应用程序设置以及如何检索这些设置。

using System;
using System.IO;
using System.Security.Permissions;

// Store and retrieve application settings.
class AppSettings
{
    const string fileName = "AppSettings#@@#.dat";
    float  aspectRatio;
    string lookupDir;
    int    autoSaveTime;
    bool   showStatusBar;

    public AppSettings()
    {
        // Create default application settings.
        aspectRatio   = 1.3333F;
        lookupDir     = @"C:\AppDirectory";
        autoSaveTime  = 30;
        showStatusBar = false;

        if(File.Exists(fileName))
        {
            BinaryReader binReader =
                new BinaryReader(File.Open(fileName, FileMode.Open));
            try
            {
                // If the file is not empty,
                // read the application settings.
                // First read 4 bytes into a buffer to
                // determine if the file is empty.
                byte[] testArray = new byte[3];
                int count = binReader.Read(testArray, 0, 3);

                if (count != 0)
                {
                    // Reset the position in the stream to zero.
                    binReader.BaseStream.Seek(0, SeekOrigin.Begin);

                    aspectRatio   = binReader.ReadSingle();
                    lookupDir     = binReader.ReadString();
                    autoSaveTime  = binReader.ReadInt32();
                    showStatusBar = binReader.ReadBoolean();
                }
            }

            // If the end of the stream is reached before reading
            // the four data values, ignore the error and use the
            // default settings for the remaining values.
            catch(EndOfStreamException e)
            {
                Console.WriteLine("{0} caught and ignored. " +
                    "Using default values.", e.GetType().Name);
            }
            finally
            {
                binReader.Close();
            }
        }

    }

    // Create a file and store the application settings.
    public void Close()
    {
        using(BinaryWriter binWriter =
            new BinaryWriter(File.Open(fileName, FileMode.Create)))
        {
            binWriter.Write(aspectRatio);
            binWriter.Write(lookupDir);
            binWriter.Write(autoSaveTime);
            binWriter.Write(showStatusBar);
        }
    }

    public float AspectRatio
    {
        get{ return aspectRatio; }
        set{ aspectRatio = value; }
    }

    public string LookupDir
    {
        get{ return lookupDir; }
        set{ lookupDir = value; }
    }

    public int AutoSaveTime
    {
        get{ return autoSaveTime; }
        set{ autoSaveTime = value; }
    }

    public bool ShowStatusBar
    {
        get{ return showStatusBar; }
        set{ showStatusBar = value; }
    }
}

class Test
{
    static void Main()
    {
        // Load application settings.
        AppSettings appSettings = new AppSettings();
        Console.WriteLine("App settings:\nAspect Ratio: {0}, " +
            "Lookup directory: {1},\nAuto save time: {2} minutes, " +
            "Show status bar: {3}\n",
            new Object[4]{appSettings.AspectRatio.ToString(),
            appSettings.LookupDir, appSettings.AutoSaveTime.ToString(),
            appSettings.ShowStatusBar.ToString()});

        // Change the settings.
        appSettings.AspectRatio   = 1.250F;
        appSettings.LookupDir     = @"C:\Temp";
        appSettings.AutoSaveTime  = 10;
        appSettings.ShowStatusBar = true;

        // Save the new settings.
        appSettings.Close();
    }
}

继承层次结构

System.Object

System.IO.BinaryWriter

命名空间

namespace: System.IO

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

线程安全

此类型的任何公共 static(在 Visual Basic 中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。

版本信息

.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 系统要求。