Reputation: 103
I would like to write the three byte arrays into the file. And, later I need to read the same way. Is it possible in C#?. Consider the below example,
byte[] source = new byte[0];
byte[] delim = new byte[0];
byte[] dest = new byte[0];
So, now I planned to write all this three byte arrays together with single file as like below,
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);
After sometime, I would like to read the file and split the source and dest byte array based on delim. Is it possible?. If yes, how I can achieve this? Any sample code would be much appreciated.
Thanks in advance for your help.
Upvotes: 0
Views: 1853
Reputation: 39122
You could use a BinaryWriter and a BinaryReader as shown below. First write the length of the array as an int32, then write the array bytes. Repeat for the second array. In reverse, read the length of the array as an int32, then read that many bytes. Repeat for the second array:
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));
Output:
source = 1 2
dest = 2 4 8 16 32 64
source2 = 1 2
dest2 = 2 4 8 16 32 64
Upvotes: 2