C# BinaryReader類

C# BinaryReader類用於從流中讀取二進制信息。它在System.IO命名空間中定義。它還支持在特定編碼中讀取字符串。

C# BinaryReader示例

我們來看看使用BinaryReader類從dat類型文件讀取數據的簡單例子。

using System;
using System.IO;
namespace BinaryWriterExample
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteBinaryFile();
            ReadBinaryFile();
            Console.ReadKey();
        }
        static void WriteBinaryFile()
        {
            using (BinaryWriter writer = new BinaryWriter(File.Open("e:\\binaryfile.dat", FileMode.Create)))
            {

                writer.Write(250);
                writer.Write("this is string data");
                writer.Write(true);
            }
        }
        static void ReadBinaryFile()
        {
            using (BinaryReader reader = new BinaryReader(File.Open("e:\\binaryfile.dat", FileMode.Open)))
            {
                Console.WriteLine("Double Value : " + reader.ReadDouble());
                Console.WriteLine("String Value : " + reader.ReadString());
                Console.WriteLine("Boolean Value : " + reader.ReadBoolean());
            }
        }
    }
}

執行上面示例代碼,得到以下結果 -

Double Value : 250
String Value : this is string data
Boolean Value : true