Search code examples
c#hexbyteraw-data

How do i edit raw data from a file in bytes?


I want to edit raw data from files (Hex) but i don't know how can i do it

Is there any package that can help me?

Also how do i convert strings in raw bytes?

I've tried some solutions out of google but none of these worked


Solution

  • Here's a function that:

    1. Reads all the bytes from a file
    2. Changes the second byte to the decimal value 8
    3. Writes the bytes back to the file

    Note, this is not the most efficient way to do this, but it's an example.

    public async Task ChangeSomeBytesInFileAsync(string path)
    {
        var bytes = await File.ReadAllBytesAsync(path);
    
        bytes[2] = 0b0000_01000;
        
        await File.WriteAllBytesAsync(path, bytes);
     }
    

    To get the bytes of a string use the Encoding class and the appropriate encoding In this example, I'm using UTF-8.

    var bytes = Encoding.UTF8.GetBytes(@"some value");