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(12.5);
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());
}
}
}
}
【C# BinaryReader用法】输出:
Double Value : 12.5
String Value : this is string data
Boolean Value : true
推荐阅读
- C# StringWriter用法
- C# TextReader用法
- C# TextWriter用法
- C#用户定义的异常
- C#文件流
- C# finally块
- C# try-catch用法
- C#异常处理
- C#字符串