2016-04-19 4 views
1

Ich bin auf der Suche nach einem großen Abschnitt von Bytes in einer Datei, entfernen Sie sie und importieren Sie dann einen neuen großen Abschnitt von Bytes beginnend wo die alten gestartet wurden.Wie finden und ersetzen Sie einen großen Abschnitt von Bytes in einer Datei?

Hier ist ein Video des manuellen Prozesses, ich versuche in C# neu zu erstellen, könnte es ihm ein wenig besser erklären: https://www.youtube.com/watch?v=_KNx8WTTcVA

Ich habe nur grundlegende Erfahrung mit C#, so lerne, wie ich entlang gehen , jede Hilfe mit diesem würde sehr geschätzt werden!

Danke.

Antwort

1

auf diese Frage finden: C# Replace bytes in Byte[]

die folgende Klasse verwenden:

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; 
    } 
} 

Verbrauch:

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) 

Das Problem ist, wenn die Datei zu groß ist, dann benötigen Sie ein "Fensterfunktion" -Funktion. Laden Sie nicht alle Bytes im Speicher, da sie viel Speicherplatz benötigen.

Verwandte Themen