我有一个二进制文件(即,它包含值在 0x00 和 0xFF 之间的字节)。我想使用 Regex 查找和编辑文件中的 ASCII 字符串(例如,“Hello World”)。然后我需要写出编辑后的文件,使其与旧文件完全相同,但已执行了我的 ASCII 编辑。如何?
byte[] inbytes = File.ReadAllBytes(wfile);
string instring = utf8.GetString(inbytes);
// use Regex to find/replace some text within instring
byte[] outbytes = utf8.GetBytes(instring);
File.WriteAllBytes(outfile, outbytes);
即使我不做任何编辑,输出文件也不同于输入文件。发生了什么事,我该怎么做?
编辑:好的,我正在尝试使用提供的建议,但无法理解如何实际实施它。这是我的示例代码:
string infile = @"C:\temp\in.dat";
string outfile = @"C:\temp\out.dat";
Regex re = new Regex(@"H[a-z]+ W[a-z]+"); // looking for "Hello World"
byte[] inbytes = File.ReadAllBytes(infile);
string instring = new SoapHexBinary(inbytes).ToString();
Match match = re.Match(instring);
if (match.Success)
{
// do work on 'instring'
}
File.WriteAllBytes(outfile, SoapHexBinary.Parse(instring).Value);
显然,我知道我不会那样做匹配,但如果我将我的正则表达式转换为字符串(或其他),那么我不能使用匹配等。有什么想法吗?谢谢!