3

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

In PHP, 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 I get it in C#?

3 Answers 3

1
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);

}
Sign up to request clarification or add additional context in comments.

Comments

0

Use File.ReadAllBytes to read the bytes of a file as a byte array.

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

If you want to convert this to a hex string (and I'd in general I'd advise against doing so - strings are immutable in C# so modifying even a single byte will require copying the rest of the string) you can for example use:

string hex = BitConverter.ToString(bytes);

Comments

0

You ask about writting to file, but you PHP code is for reading. For working with files you can use FileStream class

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.