2016-04-19 2 views
1

Я ищу, чтобы найти большой раздел байтов в файле, удалить их, а затем импортировать новую большую часть байтов, начиная с старых.Как найти и заменить большой раздел байтов в файле?

Вот видео ручного процесса, который я пытаюсь воссоздать в C#, это могло бы объяснить это немного лучше: https://www.youtube.com/watch?v=_KNx8WTTcVA

Я только базовый опыт работы с C#, так я учусь, как я иду вдоль , любая помощь с этим была бы очень оценена!

Спасибо.

ответ

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) 

Проблема, когда файл слишком велик, то вам требуется «оконная» функция. Не загружайте все байты в памяти, так как они занимают много места.

Смежные вопросы