【发布时间】:2013-08-08 13:17:19
【问题描述】:
在敲了几个小时之后,我束手无策。我在“68 39 30 00 00”的文件中有一个十六进制字符串。 “39 30”是我要替换的十进制值“12345”,“68”和“00 00”只是为了确保有一个匹配。
我想传入一个新的十进制值,例如“12346”,并替换文件中的现有值。我尝试在十六进制、字节数组等之间转换所有内容,感觉它必须比我想象的要简单得多。
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();
}
【问题讨论】:
-
那么,你是说你的出发点是一个字符串文字“6839300000”的TEXT文件吗?
-
这是一个 EXE 文件,硬编码值为“12345”,十六进制编辑器中的值为“39 30”,而“68 39 30 00 00”是我要搜索的完整十六进制字符串替换和替换。
-
如果您替换 EXE 中的值,可能会因为各种校验和等原因而无法运行。此外,EXE 是二进制文件而不是字符串。仅仅因为您可以将其视为字符串,所以它不是并将存储为字节。所以你需要用正确的数据重写字节流。请问为什么你要修改EXE文件?!
-
这是一个服务器应用程序的 alpha 版本,当前具有硬编码的端口绑定。通过十六进制编辑器或替代工具(即这样做的目的)更改值可以正常工作,直到稍后添加该功能。我只需要自己添加命令行控件,其他工具只有 GUI。
标签: c# replace hex bytearray filestream