C# 如何替换二进制文件中的unicode字符串?
我一直试图让我的程序在二进制文件中替换unicode。 用户将输入要查找的内容,程序将查找并替换为特定字符串(如果可以找到) 我到处找了找,但我找不到我的具体情况,我想要的是:C# 如何替换二进制文件中的unicode字符串?,c#,unicode,C#,Unicode,我一直试图让我的程序在二进制文件中替换unicode。 用户将输入要查找的内容,程序将查找并替换为特定字符串(如果可以找到) 我到处找了找,但我找不到我的具体情况,我想要的是: string text = File.ReadAllText(path, Encoding.Unicode); text = text.Replace(userInput, specificString); File.WriteAllText(path, text); 但任何类似的方式都应该足够了。 但是,使用它会导致
string text = File.ReadAllText(path, Encoding.Unicode);
text = text.Replace(userInput, specificString);
File.WriteAllText(path, text);
但任何类似的方式都应该足够了。
但是,使用它会导致文件变大,无法使用
我使用:
int var = File.ReadAllText(path, Encoding.Unicode).Contains(userInput) ? 1 : 0;
if (var == 1)
{
//Missing Part
}
用于检查文件是否包含用户输入的字符串(如果有关系)。这只能在非常有限的情况下工作。不幸的是,您没有提供足够的关于二进制文件性质的详细信息,让任何人都知道这是否适用于您的情况。实际上,二进制文件格式种类繁多,如果修改一个字节,其中至少有一部分将被视为无效,如果文件长度发生变化,更多的二进制文件格式可能被视为无效(即插入点之后的数据不再是预期的位置) 当然,许多二进制文件要么加密,要么压缩,或者两者兼而有之。在这种情况下,即使你奇迹般地找到了你正在寻找的文本,它可能实际上并不代表该文本,修改它会使文件无法使用
以上所说的,为了论证,假设你的场景没有任何问题,完全可以用一些完全不同的文本完全替换文件中间找到的一些文本。 注意,我们还需要对文本编码进行假设。文本可以用多种方式表示,您不仅需要使用正确的编码来查找文本,还需要确保替换文本的有效性。为了便于讨论,假设您的文本编码为UTF8
现在我们拥有了我们所需要的一切:void ReplaceTextInFile(string fileName, string oldText, string newText)
{
byte[] fileBytes = File.ReadAllBytes(fileName),
oldBytes = Encoding.UTF8.GetBytes(oldText),
newBytes = Encoding.UTF8.GetBytes(newText);
int index = IndexOfBytes(fileBytes, oldBytes);
if (index < 0)
{
// Text was not found
return;
}
byte[] newFileBytes =
new byte[fileBytes.Length + newBytes.Length - oldBytes.Length];
Buffer.BlockCopy(fileBytes, 0, newFileBytes, 0, index);
Buffer.BlockCopy(newBytes, 0, newFileBytes, index, newBytes.Length);
Buffer.BlockCopy(fileBytes, index + oldBytes.Length,
newFileBytes, index + newBytes.Length,
fileBytes.Length - index - oldBytes.Length);
File.WriteAllBytes(filename, newFileBytes);
}
int IndexOfBytes(byte[] searchBuffer, byte[] bytesToFind)
{
for (int i = 0; i < searchBuffer.Length - bytesToFind.Length; i++)
{
bool success = true;
for (int j = 0; j < bytesToFind.Length; j++)
{
if (searchBuffer[i + j] != bytesToFind[j])
{
success = false;
break;
}
}
if (success)
{
return i;
}
}
return -1;
}
void replacetextinfle(字符串文件名、字符串旧文本、字符串新文本)
{
byte[]fileBytes=File.ReadAllBytes(文件名),
oldBytes=Encoding.UTF8.GetBytes(oldText),
newBytes=Encoding.UTF8.GetBytes(newText);
int index=IndexOfBytes(fileBytes,oldBytes);
如果(指数<0)
{
//找不到文本
返回;
}
字节[]新文件字节=
新字节[fileBytes.Length+newBytes.Length-oldBytes.Length];
BlockCopy(fileBytes,0,newFileBytes,0,index);
块复制(新字节,0,新文件字节,索引,新字节,长度);
Buffer.BlockCopy(fileBytes,index+oldBytes.Length,
新文件字节,索引+新字节。长度,
fileBytes.Length-index-oldBytes.Length);
File.writealBytes(文件名,newFileBytes);
}
int IndexOfBytes(字节[]搜索缓冲区,字节[]ByTestOfId)
{
for(int i=0;i
注:
- 上述情况具有破坏性。您可能希望只在文件的副本上运行它,或者更愿意修改代码,以便它接受一个附加参数,指定修改应写入的新文件
- 此实现在内存中完成所有操作。这要方便得多,但是如果您处理的是大文件,尤其是在32位平台上,您可能会发现需要以较小的块处理文件