C# 学习之BinaryWriter 和 BinaryReader

C# BinaryWriter类用于将二进制信息写入流中。它在System.IO命名空间中找到。它还支持以特定编码编写字符串。

C# BinaryWriter示例

using System;  
using System.IO;  
namespace BinaryWriterExample  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            string fileName = "e:\\binaryfile.dat";  
            using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))  
            {  
                writer.Write(1024);  
                writer.Write("this is string data");  
                writer.Write(true);  
            }  
            Console.WriteLine("Data written successfully...");    
        }  
    }  
}

执行上面示例代码,得到以下结果 -


Data written successfully...

C# BinaryReader类用于从流中读取二进制信息。它在System.IO命名空间中定义。它还支持在特定编码中读取字符串。

C# BinaryReader示例

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

你可能感兴趣的:(C#学习笔记)