c# - 将多个字节[]写入和读取到文件C#中
问题描述
我想将三个字节数组写入文件。而且,稍后我需要以同样的方式阅读。在 C# 中可能吗?考虑下面的例子,
byte[] source = new byte[0];
byte[] delim = new byte[0];
byte[] dest = new byte[0];
因此,现在我计划将所有这三个字节数组与单个文件一起编写,如下所示,
byte[] writeData = new byte[source.Length + delim.Length + dest.Length];
Buffer.BlockCopy(source, 0, writeData, 0, source.Length);
Buffer.BlockCopy(delim, 0, writeData, source.Length, delim.Length);
Buffer.BlockCopy(dest, 0, writeData, source.Length + delim.Length, dest.Length);
File.WriteAllBytes("myfile.txt", writeData);
一段时间后,我想读取文件并根据 delim 拆分源和目标字节数组。是否可以?。如果是,我怎么能做到这一点?任何示例代码将不胜感激。
在此先感谢您的帮助。
解决方案
您可以使用BinaryWriter和BinaryReader,如下所示。首先将数组的长度写入 int32,然后写入数组字节。对第二个数组重复。相反,将数组的长度读取为 int32,然后读取那么多字节。对第二个数组重复:
byte[] source = new byte[2] { 1, 2 };
byte[] dest = new byte[6] { 2, 4, 8, 16, 32, 64 };
using (FileStream fs = new FileStream("myFile.txt", FileMode.OpenOrCreate))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(source.Length);
bw.Write(source, 0, source.Length);
bw.Write(dest.Length);
bw.Write(dest, 0, dest.Length);
}
}
byte[] source2;
byte[] dest2;
using (FileStream fs = new FileStream("myFile.txt", FileMode.Open))
{
using (BinaryReader br = new BinaryReader(fs))
{
source2 = br.ReadBytes(br.ReadInt32());
dest2 = br.ReadBytes(br.ReadInt32());
}
}
Console.WriteLine("source = " + String.Join(" ", source));
Console.WriteLine("dest = " + String.Join(" ", dest));
Console.WriteLine("source2 = " + String.Join(" ", source2));
Console.WriteLine("dest2 = " + String.Join(" ", dest2));
输出:
source = 1 2
dest = 2 4 8 16 32 64
source2 = 1 2
dest2 = 2 4 8 16 32 64
推荐阅读
- google-calendar-api - 谷歌日历 API grantOfflineAccess() 没有弹出
- r - 无论列顺序如何,计算所有可能的组合
- validation - 时间字段中的 XPAGE validateexpression 问题
- matlab - 创建一个估计 e 并概述误差的 MATLAB 函数
- java - 使用 JVM 将堆保存到文件后,标量替换对象的重新分配失败
- javascript - 计算具有不同 id 和名称 attr 的动态创建的文本区域的字符
- xml - 未解决的参考:合成
- java - 如何填充动态列表 Java
- c# - 在 WPF 应用程序中使用 Net Driver 查询 Neo4j 并返回找到的节点
- sql - 使用 nvarchar(MAX) 的索引与基于具有固定字符的 nvarchar 的索引的性能?