🐋作者简介:博主是一位.Net开发者,同时也是RPA和低代码平台的践行者。
🐬个人主页: 会敲键盘的肘子
🐰系列专栏: .Net实用方法总结
🦀专栏简介:博主针对.Net开发和C站问答过程中遇到的问题进行总结,形成本专栏,希望可以帮助到您解决问题。
🐶座右铭:总有一天你所坚持的会反过来拥抱你。
🌈写在前面:本文主要介绍System.IO命名空间的BinaryWriter 类,介绍其常用的方法和示例说明。
👉本文关键字:System.IO、BinaryWriter类、方法示例、C#
[TOC]
1️⃣ System.IO命名空间
.NET中的IO操作命名空间,包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。
我们在.NET中的IO操作,经常需要调用一下几个类。
- FileStream类
文件流类,负责大文件的拷贝,读写。
- Path类
Path类中方法,基本都是对字符串(文件名)的操作,与实际文件没多大关系。
- File类
File类可以进行一些对小文件拷贝、剪切操作,还能读一些文档文件。
- Dirctory类
目录操作,创建文件、删除目录,获取目录下文件名等等。
2️⃣ BinaryWriter类
♈ 定义
将二进制中的基元类型写入流并支持用特定的编码写入字符串。
public class BinaryWriter : IAsyncDisposable, IDisposable
示例
下面的代码示例演示如何在文件中存储和检索应用程序设置。
using System;
using System.IO;
using System.Text;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (var stream = File.Open(fileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;
if (File.Exists(fileName))
{
using (var stream = File.Open(fileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}
}
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}
此类型实现 IDisposable 接口。 使用从此类型派生的任何类型后,应直接或间接释放它。 若要直接释放类型,请在try
/catch
块中调用其 Dispose 方法。 若要间接释放类型,请使用using
(在 C# 中)或Using
(在 Visual Basic 中)等语言构造。 有关详细信息,请参阅接口主题中的 IDisposable Dispose 和“使用实现 IDisposable 的对象”部分。
♊ 属性
BaseStream 获取 BinaryWriter 的基础流
public virtual System.IO.Stream BaseStream { get; }
示例
下面的代码示例演示如何使用类顶部MemoryStream的BinaryReader类BinaryWriter
读取和写入Double
内存中的数据。 MemoryStream
仅读取和写入 Byte
数据。
using System;
using System.IO;
class BinaryRW
{
static void Main()
{
int i;
const int arrayLength = 1000;
// Create random data to write to the stream.
Random randomGenerator = new Random();
double[] dataArray = new double[arrayLength];
for(i = 0; i < arrayLength; i++)
{
dataArray[i] = 100.1 * randomGenerator.NextDouble();
}
using(BinaryWriter binWriter =
new BinaryWriter(new MemoryStream()))
{
// Write the data to the stream.
Console.WriteLine("Writing data to the stream.");
for(i = 0; i < arrayLength; i++)
{
binWriter.Write(dataArray[i]);
}
// Create a reader using the stream from the writer.
using(BinaryReader binReader =
new BinaryReader(binWriter.BaseStream))
{
try
{
// Return to the beginning of the stream.
binReader.BaseStream.Position = 0;
// Read and verify the data.
Console.WriteLine("Verifying the written data.");
for(i = 0; i < arrayLength; i++)
{
if(binReader.ReadDouble() != dataArray[i])
{
Console.WriteLine("Error writing data.");
break;
}
}
Console.WriteLine("The data was written " +
"and verified.");
}
catch(EndOfStreamException e)
{
Console.WriteLine("Error writing data: {0}.",
e.GetType().Name);
}
}
}
}
}
♌ 常用方法
Close() 关闭
public virtual void Close ();
注意:此方法调用 Dispose ,指定true
以释放所有资源。 不需要专门调用 Close 方法。 请确保 Stream 已正确释放每个对象。 可以 Streamusing
Using
在 Visual Basic) 中 (或块中声明对象,以确保释放流及其所有资源,或者可以显式调用 Dispose 方法。
Dispose() 释放
public void Dispose ();
Flush() 清除此流的缓冲区,使得所有缓冲数据都写入到文件中
public virtual void Flush ();
Write(Boolean) 将单字节 Boolean
值写入当前流,其中 0 表示 false
,1 表示 true
public virtual void Write (bool value);
参数
value
要写入的
Boolean
值(0 或 1)。
示例
下面的代码示例演示如何在文件中存储和检索应用程序设置。
using System;
using System.IO;
using System.Text;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (var stream = File.Open(fileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;
if (File.Exists(fileName))
{
using (var stream = File.Open(fileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}
}
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}
Write(Byte) 将一个无符号字节写入当前流,并将流的位置提升 1 个字节
public virtual void Write (byte value);
参数
value
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);
}
}
}
Write(Byte[]) 将字节数组写入基础流
public virtual void Write (byte[] buffer);
参数
buffer
Byte[]
包含要写入的数据的字节数组。
示例
下面的代码示例演示如何使用内存作为后盾存储编写二进制数据,然后验证数据是否已正确写入。
using System;
using System.IO;
class BinaryRW
{
static void Main()
{
const int arrayLength = 1000;
// Create random data to write to the stream.
byte[] dataArray = new byte[arrayLength];
new Random().NextBytes(dataArray);
BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
// Write the data to the stream.
Console.WriteLine("Writing the data.");
binWriter.Write(dataArray);
// Create the reader using the stream from the writer.
BinaryReader binReader =
new BinaryReader(binWriter.BaseStream);
// Set Position to the beginning of the stream.
binReader.BaseStream.Position = 0;
// Read and verify the data.
byte[] verifyArray = binReader.ReadBytes(arrayLength);
if(verifyArray.Length != arrayLength)
{
Console.WriteLine("Error writing the data.");
return;
}
for(int i = 0; i < arrayLength; i++)
{
if(verifyArray[i] != dataArray[i])
{
Console.WriteLine("Error writing the data.");
return;
}
}
Console.WriteLine("The data was written and verified.");
}
}
Write(Byte[], Int32, Int32) 将字节数组区域写入当前流
public virtual void Write (byte[] buffer, int index, int count);
参数
buffer
Byte[]
包含要写入的数据的字节数组。
index
要从
buffer
中读取且要写入流的第一个字节的索引。
count
要从
buffer
中读取且要写入流的字节数。
示例
下面的代码示例演示如何使用内存编写二进制数据作为后盾存储,然后验证数据是否已正确写入。
using System;
using System.IO;
namespace BinaryRW
{
class Program
{
static void Main(string[] args)
{
const int arrayLength = 1000;
byte[] dataArray = new byte[arrayLength];
byte[] verifyArray = new byte[arrayLength];
new Random().NextBytes(dataArray);
using (BinaryWriter binWriter = new BinaryWriter(new MemoryStream()))
{
Console.WriteLine("Writing the data.");
binWriter.Write(dataArray, 0, arrayLength);
using (BinaryReader binReader = new BinaryReader(binWriter.BaseStream))
{
binReader.BaseStream.Position = 0;
if (binReader.Read(verifyArray, 0, arrayLength) != arrayLength)
{
Console.WriteLine("Error writing the data.");
return;
}
}
}
for (int i = 0; i < arrayLength; i++)
{
if (verifyArray[i] != dataArray[i])
{
Console.WriteLine("Error writing the data.");
return;
}
}
Console.WriteLine("The data was written and verified.");
}
}
}
Write(Char[], Int32, Int32) 将字符的子数组写入文本流
public virtual void Write (char[] buffer, int index, int count);
参数
buffer
Char[]
要从中写出数据的字符数组。
index
在开始接收数据时缓存中的字符位置。
count
要写入的字符数。
示例
下面的代码示例演示如何使用内存作为后盾存储来读取和写入数据。
using System;
using System.IO;
class BinaryRW
{
static void Main()
{
char[] invalidPathChars = Path.InvalidPathChars;
MemoryStream memStream = new MemoryStream();
BinaryWriter binWriter = new BinaryWriter(memStream);
// Write to memory.
binWriter.Write("Invalid file path characters are: ");
binWriter.Write(
Path.InvalidPathChars, 0, Path.InvalidPathChars.Length);
// Create the reader using the same MemoryStream
// as used with the writer.
BinaryReader binReader = new BinaryReader(memStream);
// Set Position to the beginning of the stream.
memStream.Position = 0;
// Read the data from memory and write it to the console.
Console.Write(binReader.ReadString());
int arraySize = (int)(memStream.Length - memStream.Position);
char[] memoryData = new char[arraySize];
binReader.Read(memoryData, 0, arraySize);
Console.WriteLine(memoryData);
}
}
Write(Double) 将 8 字节浮点值写入当前流,并将流的位置提升 8 个字节
public virtual void Write (double value);
参数
value
要写入的 8 字节浮点值。
示例
下面的代码示例演示如何使用类顶部MemoryStream的BinaryReader类BinaryWriter
读取和写入Double
内存中的数据。 MemoryStream
仅读取和写入 Byte
数据。
using System;
using System.IO;
class BinaryRW
{
static void Main()
{
int i;
const int arrayLength = 1000;
// Create random data to write to the stream.
Random randomGenerator = new Random();
double[] dataArray = new double[arrayLength];
for(i = 0; i < arrayLength; i++)
{
dataArray[i] = 100.1 * randomGenerator.NextDouble();
}
using(BinaryWriter binWriter =
new BinaryWriter(new MemoryStream()))
{
// Write the data to the stream.
Console.WriteLine("Writing data to the stream.");
for(i = 0; i < arrayLength; i++)
{
binWriter.Write(dataArray[i]);
}
// Create a reader using the stream from the writer.
using(BinaryReader binReader =
new BinaryReader(binWriter.BaseStream))
{
try
{
// Return to the beginning of the stream.
binReader.BaseStream.Position = 0;
// Read and verify the data.
Console.WriteLine("Verifying the written data.");
for(i = 0; i < arrayLength; i++)
{
if(binReader.ReadDouble() != dataArray[i])
{
Console.WriteLine("Error writing data.");
break;
}
}
Console.WriteLine("The data was written " +
"and verified.");
}
catch(EndOfStreamException e)
{
Console.WriteLine("Error writing data: {0}.",
e.GetType().Name);
}
}
}
}
}
Write(Half) 将双字节浮点值写入当前流,并将流位置提升两个字节
public virtual void Write (Half value);
参数
value
要写入的双字节浮点值。
示例
下面的代码示例演示如何使用类顶部MemoryStream的BinaryReader类BinaryWriter
读取和写入Double
内存中的数据。 MemoryStream
仅读取和写入 Byte
数据。
using System;
using System.IO;
class BinaryRW
{
static void Main()
{
int i;
const int arrayLength = 1000;
// Create random data to write to the stream.
Random randomGenerator = new Random();
double[] dataArray = new double[arrayLength];
for(i = 0; i < arrayLength; i++)
{
dataArray[i] = 100.1 * randomGenerator.NextDouble();
}
using(BinaryWriter binWriter =
new BinaryWriter(new MemoryStream()))
{
// Write the data to the stream.
Console.WriteLine("Writing data to the stream.");
for(i = 0; i < arrayLength; i++)
{
binWriter.Write(dataArray[i]);
}
// Create a reader using the stream from the writer.
using(BinaryReader binReader =
new BinaryReader(binWriter.BaseStream))
{
try
{
// Return to the beginning of the stream.
binReader.BaseStream.Position = 0;
// Read and verify the data.
Console.WriteLine("Verifying the written data.");
for(i = 0; i < arrayLength; i++)
{
if(binReader.ReadDouble() != dataArray[i])
{
Console.WriteLine("Error writing data.");
break;
}
}
Console.WriteLine("The data was written " +
"and verified.");
}
catch(EndOfStreamException e)
{
Console.WriteLine("Error writing data: {0}.",
e.GetType().Name);
}
}
}
}
}
Write(Int32) 将 4 字节带符号整数写入当前流,并将流的位置提升 4 个字节
public virtual void Write (int value);
参数
value
要写入的 4 字节带符号整数。
示例
下面的代码示例演示如何在文件中存储和检索应用程序设置。
using System;
using System.IO;
using System.Text;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (var stream = File.Open(fileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;
if (File.Exists(fileName))
{
using (var stream = File.Open(fileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}
}
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}
Write(Single) 将 4 字节浮点值写入当前流,并将流的位置提升 4 个字节
public virtual void Write (float value);
参数
value
要写入的 4 字节浮点值。
示例
下面的代码示例演示如何在文件中存储和检索应用程序设置。
using System;
using System.IO;
using System.Text;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (var stream = File.Open(fileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;
if (File.Exists(fileName))
{
using (var stream = File.Open(fileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}
}
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}
Write(String) 将有长度前缀的字符串按 BinaryWriter 的当前编码写入此流,并根据所使用的编码和写入流的特定字符,提升流的当前位置
public virtual void Write (string value);
参数
value
String
要写入的 4 字节带符号整数。
示例
下面的代码示例演示如何在文件中存储和检索应用程序设置。
using System;
using System.IO;
using System.Text;
class ConsoleApplication
{
const string fileName = "AppSettings.dat";
static void Main()
{
WriteDefaultValues();
DisplayValues();
}
public static void WriteDefaultValues()
{
using (var stream = File.Open(fileName, FileMode.Create))
{
using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;
if (File.Exists(fileName))
{
using (var stream = File.Open(fileName, FileMode.Open))
{
using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}
}
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}
♎ 更多方法
更多方法请查阅官方文档 BinaryWriter类。
⭐写在结尾:文章中出现的任何错误请大家批评指出,一定及时修改。
希望写在这里的小伙伴能给个三连支持!