何時間も頭をぶつけた後、私は頭がおかしくなりました。ファイルに「68 39 30 00 00」という 16 進文字列があります。「39 30」は、置き換えたい 10 進数の「12345」です。「68」と「00 00」は、1 つの一致を確実にするためのものです。
「12346」などの新しい 10 進数値を渡し、ファイル内の既存の値を置き換えたいと考えています。私は 16 進数、バイト配列などの間ですべてを前後に変換しようとしましたが、私が考えているよりもはるかに単純でなければならないと感じています。
static void Main(string[] args)
{
// Original Byte string to find and Replace "12345"
byte[] original = new byte[] { 68, 39, 30, 00, 00 };
int newPort = Convert.ToInt32("12346");
string hexValue = newPort.ToString("X2");
byte[] byteValue = StringToByteArray(hexValue);
// Build Byte Array of the port to replace with. Starts with /x68 and ends with /x00/x00
byte[] preByte = new byte[] { byte.Parse("68", System.Globalization.NumberStyles.HexNumber) };
byte[] portByte = byteValue;
byte[] endByte = new byte[] { byte.Parse("00", System.Globalization.NumberStyles.HexNumber), byte.Parse("00", System.Globalization.NumberStyles.HexNumber) };
byte[] replace = new byte[preByte.Length + portByte.Length + endByte.Length];
preByte.CopyTo(replace, 0);
portByte.CopyTo(replace, preByte.Length);
endByte.CopyTo(replace, (preByte.Length + portByte.Length));
Patch("Server.exe", "Server1.exe", original, replace);
}
static private byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}