How to combine two byte arrays with a delimiter between them, in C #


My question is simply how I could put two byte arrays together and delimit them. In the following example, I write them and write them as a single file. But, First I do not know how I could join them with a delimiter, a comma or something to separate them and that when I start my program I will be able to obtain them by means of a split. The code is as follows:

//Everything seems fine -> Reading bytes
Console.WriteLine("[*] Reading Data...");
byte[] plainBytes = File.ReadAllBytes(file);

//Yep, got bytes -> Encoding
Console.WriteLine("[*] Encoding Data...");
byte[] encodedBytes = encodeBytes(plainBytes, pass);

Console.WriteLine("[*] Save to Output File... ");

//Leer el fichero
Console.WriteLine("[*] Reading fichero...");
byte[] Stub = File.ReadAllBytes("rutafichero");

// ::: Create new List of bytes
var list = new List<byte>();

// ::: Call ToArray to convert List to array
byte[] resultado = list.ToArray();

//write bytes
File.WriteAllBytes(outFile, resultado);

//File.WriteAllBytes(outFile, encodedBytes);

Console.WriteLine("\n[*] File successfully encoded!");

Then my first byte array (file 1) will be joined + with the other byte array (file 2) and it will be written in a single file. When I start the resulting file I will be able to get the two arrays by means of a split. That is the objective that I wanted to carry out and that unfortunately I did not know as first because I do not know delimitar dos byte array combinados and second how to extract them later. The goal was to do it with an assembly.

asked by Sergio Ramos 09.05.2017 в 01:34

1 answer


Personally, if you want to write 2 arrays in a file and be able to read them separately later, I would use the class BinaryWriter , so that you do everything automatic. The idea of using a split with a comma does not sound good in this case.

For example, according to your example, starting with the following 2 byte arrays:

byte[] encodedBytes = ...;
byte[] Stub = ...;

You can write the 2 arrays to a file as follows:

using (var writer = new BinaryWriter(File.Open(outFile, FileMode.Create)))

And then you can recover them using the class BinaryReader as follows:

using (var reader = new BinaryReader(File.Open(outFile, FileMode.Open)))
    encodedBytes = reader.ReadBytes(reader.ReadInt32());
    Stub = reader.ReadBytes(reader.ReadInt32());
answered by 09.05.2017 / 02:24