将多个字节[]写入文件C#

问题描述 投票:0回答:1

我想将三个字节数组写入文件。而且,以后我需要以相同的方式阅读。在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拆分源字节和目标字节数组。可能吗?。如果可以,我该如何实现?任何示例代码将不胜感激。

感谢您的帮助。

c# arrays byte delimiter binaryfiles
1个回答
0
投票

您可以如下所示使用BinaryWriterBinaryReader。首先将数组的长度写为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
© www.soinside.com 2019 - 2024. All rights reserved.