将多个 byte[] 写入和读取文件 C#

Write and read the multiple byte[] into the file 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 and a 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