1
我正在寻找一个文件中的大部分字节,删除它们,然后导入新的大部分字节,从旧的字节开始。如何查找并替换文件中的大部分字节?
下面是我想在C#中重新创建手动过程的视频,这或许可以解释它好一点:https://www.youtube.com/watch?v=_KNx8WTTcVA
我与C#只有基本的经验,所以我学习,我走,任何帮助,将非常感激!
感谢。
我正在寻找一个文件中的大部分字节,删除它们,然后导入新的大部分字节,从旧的字节开始。如何查找并替换文件中的大部分字节?
下面是我想在C#中重新创建手动过程的视频,这或许可以解释它好一点:https://www.youtube.com/watch?v=_KNx8WTTcVA
我与C#只有基本的经验,所以我学习,我走,任何帮助,将非常感激!
感谢。
参考这个问题: C# Replace bytes in Byte[]
使用下面的类:
public static class BytePatternUtilities
{
private static int FindBytes(byte[] src, byte[] find)
{
int index = -1;
int matchIndex = 0;
// handle the complete source array
for (int i = 0; i < src.Length; i++)
{
if (src[i] == find[matchIndex])
{
if (matchIndex == (find.Length - 1))
{
index = i - matchIndex;
break;
}
matchIndex++;
}
else
{
matchIndex = 0;
}
}
return index;
}
public static byte[] ReplaceBytes(byte[] src, byte[] search, byte[] repl)
{
byte[] dst = null;
byte[] temp = null;
int index = FindBytes(src, search);
while (index >= 0)
{
if (temp == null)
temp = src;
else
temp = dst;
dst = new byte[temp.Length - search.Length + repl.Length];
// before found array
Buffer.BlockCopy(temp, 0, dst, 0, index);
// repl copy
Buffer.BlockCopy(repl, 0, dst, index, repl.Length);
// rest of src array
Buffer.BlockCopy(
temp,
index + search.Length,
dst,
index + repl.Length,
temp.Length - (index + search.Length));
index = FindBytes(dst, search);
}
return dst;
}
}
用法:
byte[] allBytes = File.ReadAllBytes(@"your source file path");
byte[] oldbytePattern = new byte[]{49, 50};
byte[] newBytePattern = new byte[]{48, 51, 52};
byte[] resultBytes = BytePatternUtilities.ReplaceBytes(allBytes, oldbytePattern, newBytePattern);
File.WriteAllBytes(@"your destination file path", resultBytes)
问题是当文件过大,那么你就需要一个“开窗”功能。不要将所有字节加载到内存中,因为它占用大量空间。