【问题标题】:How to find and replace a large section of bytes in a file?如何查找和替换文件中的大部分字节?
【发布时间】:2016-08-12 07:26:21
【问题描述】:

我希望在文件中找到一大段字节,删除它们,然后从旧字节开始处导入新的大段字节。

这是我尝试在 C# 中重新创建的手动过程的视频,它可能会更好地解释它:https://www.youtube.com/watch?v=_KNx8WTTcVA

我只有 C# 的基本经验,所以我边学边学,非常感谢任何帮助!

谢谢。

【问题讨论】:

    标签: c# binary hex byte


    【解决方案1】:

    参考这个问题: 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)
    

    问题是当文件太大时,你需要一个“窗口”功能。不要将所有字节都加载到内存中,因为它会占用大量空间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2017-01-10
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 2021-11-15
      相关资源
      最近更新 更多