How to open a file as binary mode and replace hexadecimal strings?

I need to open and edit the executable in binary mode to replace the hex value as a string.

In PHP, it looks like this:

<?php
    $fp = fopen('file.exe', 'r+');
    $content = fread($fp, filesize('file.exe'));
    fclose($fp);
    print $content;
    /* [...] This program cannot be run in DOS mode.[...] */
?>

How can I get it in C #?

+3
source share
3 answers
public void Manipulate()
{
    byte[] data = File.ReadAllBytes("file.exe");
    byte[] newData;

    //walkthrough data and do what you need to do and move to newData

    File.WriteAllBytes("new_file.exe", newData);

}
+1
source

Use File.ReadAllBytesto read bytes of a file as a byte array.

byte[] bytes = File.ReadAllBytes('file.exe');

If you want to convert this to a hexadecimal string (and I would not advise doing it at all - the strings are immutable in C #, so to modify even one byte you will need to copy the rest of the string), for example, use:

string hex = BitConverter.ToString(bytes);
0

You are asking about writing a file, but you are using PHP code to read. You can use the FileStream class to work with files.

using(FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Write))
{
    ....
    stream.WriteByte(byte);
    ....
}
0
source

Source: https://habr.com/ru/post/1782034/


All Articles