我一直在尝试让我的程序替换二进制文件中的 unicode。用户输入要查找的内容,程序将查找并用特定的字符串(如果可以找到的话)替换它。
我四处搜寻,但没有找到具体的信息,我想要的是这样的:
string text = File.ReadAllText(path, Encoding.Unicode);
text = text.Replace(userInput, specificString);
File.WriteAllText(path, text);
Run Code Online (Sandbox Code Playgroud)
但任何以类似方式工作的东西都应该足够了。但是,使用它会导致文件更大且无法使用。
我用:
int var = File.ReadAllText(path, Encoding.Unicode).Contains(userInput) ? 1 : 0;
if (var == 1)
{
//Missing Part
}
Run Code Online (Sandbox Code Playgroud)
用于检查文件是否包含用户输入的字符串(如果重要)。
这只能在非常有限的情况下起作用。不幸的是,您没有提供有关二进制文件性质的足够详细信息,以便任何人都知道这是否适用于您的情况。实际上有无数种二进制文件格式,如果您修改单个字节,至少其中一些会变得无效,如果文件长度发生变化(即插入点之后的数据被修改),则更多的可能会变得无效。不再是预期的位置)。
当然,许多二进制文件也被加密、压缩或两者兼而有之。在这种情况下,即使您奇迹般地找到了您要查找的文本,它也可能实际上并不代表该文本,并且修改它将使文件变得无法使用。
尽管如此,为了便于讨论,我们假设您的场景没有任何这些问题,并且完全可以用一些完全不同的文本完全替换文件中间找到的一些文本。
请注意,我们还需要对文本编码做出假设。文本可以用多种方式表示,您不仅需要使用正确的编码来查找文本,还要确保替换文本有效。为了便于讨论,假设您的文本编码为 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;
}
Run Code Online (Sandbox Code Playgroud)
笔记:
| 归档时间: |
|
| 查看次数: |
2089 次 |
| 最近记录: |