C# – File to Bytes to Stored Hex to Bytes to File

email me

This is how you would convert a file to a byte array, convert the byte array to hex values, store those hex values in a string, convert the hex values back to a byte array, and then reconstitute the original file from the stored hex values. Why would you want to do this? To store extra resource files as hex values in your code (thus, no longer requiring the files)…this works in most languages, including PowerShell and Python.

using System;
using System.IO;
using System.Globalization;

class HexBytes
{

// convert byte array from file to hex values
public static string ConvertByteToHex(byte[] byteData)
{
string hexValues = BitConverter.ToString(byteData).Replace("-", "");

return hexValues;
}

// convert hex values of file back to bytes
public static byte[] ConvertHexToByteArray(string hexString)
{
byte[] byteArray = new byte[hexString.Length / 2];

for (int index = 0; index < byteArray.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
byteArray[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}

return byteArray;
}

// entry point
static void Main()
{

string Filename = @"C:\CSharp\foo1.exe";
byte[] Bytes1 = File.ReadAllBytes(Filename);

// Return Hex Values from Byte Data
Console.WriteLine(ConvertByteToHex(Bytes1));

// Hex Values for Microsoft's Sound Recorder
string StoredHexValues = "SEE Hex_Values.txt TEXT FILE";
// Convert Stored Hex Values to Bytes
byte[] Bytes2 = ConvertHexToByteArray(StoredHexValues);

// Save Converted Hex to Bytes as File.
File.WriteAllBytes((@"C:\CSharp\foo2.exe"), Bytes2);

Console.Write("\nPress any key to continue...");
Console.ReadKey();

Filename = string.Empty;
StoredHexValues = string.Empty;
Array.Clear(Bytes1, 0, Bytes1.Length);
Array.Clear(Bytes2, 0, Bytes2.Length);
}

}

Copy/paste values to StoredHexValues: Hex_Values.txt

Notes

Now, you could also store the file in base64, and convert the base64 to a byte array.

string StoredBase64 = "SEE Bytes_Values.txt TEXT FILE"
byte[] Bytes3 = Convert.FromBase64String(StoredBase64);
File.WriteAllBytes((@"C:\CSharp\foo2.exe"), Bytes3);

Copy/paste values to StoredBase64: Bytes_Values.txt

Online Base64

tags: CSharp, Byte Storage, Store EXE, MrNetTek