I have a file in which I need to add a sequence of bytes. But not with a replacement, namely add.

Tell me how to do this?

I used this code to allocate bytes and then overwrite the selected bytes. It works crookedly.

public void ExpandFile(FileStream stream, long offset, int extraBytes) { const int SIZE = 4096; var buffer = new byte[SIZE]; var length = stream.Length; stream.SetLength(length + extraBytes); var pos = length; int to_read; while (pos > offset) { to_read = pos - SIZE >= offset ? SIZE : (int)(pos - offset); pos -= to_read; stream.Position = pos; stream.Read(buffer, 0, to_read); stream.Position = pos + extraBytes; stream.Write(buffer, 0, to_read); } } 
  • one
    Paste in the middle of the file is impossible, you have to read all the data to the end and overwrite them - Andrey NOP

1 answer 1

Read bytes from the write position to the end of the file into a temporary buffer, then return to the write position and write bytes to be added, and after them write the bytes from the buffer:

 public void ExpandFile(FileStream stream, long offset, int extraBytes) { byte[] temp = new byte[stream.Length - offset]; stream.Position = offset; stream.Read(temp, 0, temp.Length); stream.Position = offset; stream.Write(BitConverter.GetBytes(extraBytes), 0, 4); stream.Write(temp, 0, temp.Length); }