How to open a file as binary mode and replace hex strings?
I need open and edit a executable file in binary mode, to replace hex value as string.
In PHP, looks like this:
<?ph开发者_运维知识库p
$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#?
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);
}
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);
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);
....
}
精彩评论