如何编辑文件中的十六进制代码?正则表达式损坏文件

How to edit hex code in a file? Regex corrupts the file

我正在尝试编辑文件的十六进制代码。 C# 中的代码需要找到解码文本,即 1004 或相应的十六进制 31 30 30 34 并替换为字符串 2113 或相应的十六进制 32 31 31 33

我尝试使用以下方法直接编辑字符串:-

string test = File.ReadAllText("tram.png");
Regex id = new Regex("1004");
string idre = id.Replace(test, "2113", 1);
File.WriteAllText("tram.png", idre);

也试过Byte方法

Byte[] test = File.ReadAllBytes("tram.png");             
Byte[] id = new Regex("1004");             
Byte[] idre = id.Replace(test, "2113", 1);
File.WriteAllBytes("tram.png", idre);

它说 'byte[]' 不包含 'Replace' 的定义并且无法将类型 'System.Text.RegularExpressions.Regex' 隐式转换为 'byte[]'

你能告诉我我做错了什么吗?

不能对字节使用正则表达式。您可以手动查找模式并替换数组中的那些元素:

byte[] bytes = File.ReadAllBytes("tram.png");

for (int i = 0; i < bytes.Length - 4; ++i)
{
    if (bytes[i] == 31 && bytes[i + 1] == 30 && bytes[i + 2] == 30 && bytes[i + 3] == 34)
    {
        bytes[i] = 32;
        bytes[i + 1] = 31;
        bytes[i + 2] = 31;
        bytes[i + 3] = 33;

        i += 3;  // Skip the new bytes for efficiency.
    }
}

File.WriteAllBytes("tram.png", bytes);