0

I'm looking at removing a large section of bytes from within a file and then inserting a new large section of bytes starting in the same place the original removed bytes did, all using C#. Does anyone know how to go about this? I can't see to find any help online.

Any help would be much appreciated!

Thanks.

3
  • What part of the process do you not understand how to do? Reading the file, editing the read file, or saving the edited file? The saving and loading part you should be able to find plenty of tutorials for Commented Apr 18, 2016 at 23:16
  • @ScottChamberlain I'm not sure how to do the hex editing part (removing the existing bytes, then adding the new ones). I've never done something like that in C# before. Commented Apr 18, 2016 at 23:36
  • When you say insert, do you mean to preserve the bytes in the destination file that are past the offset? Also how large is the data? If it extends beyond what can reasonably be held in memory there will need to be additional code to hold a buffer while transferring the bytes. Commented Apr 19, 2016 at 5:31

1 Answer 1

1

This should get you started.

Steps are as follow:

  1. Find a position you want to edit.
  2. Prepare your new data
  3. Write

.

using System;
using System.Text;
using System.IO;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {

            using (BinaryWriter writer = new BinaryWriter(File.Open("TextFile1.txt", FileMode.Open, FileAccess.ReadWrite)))
            {
                int offset = 1; //position you want to start editing
                byte[] new_data = new byte[] { 0x68, 0x69 }; //new data
                writer.Seek(offset, SeekOrigin.Begin); //move your cursor to the position
                writer.Write(new_data);//write it      
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response, would it be possible to use another BinaryWriter to fill the new_data variable with content from another file?
you can populate your buffer using BinaryReader and follow the same flow. (do it by chunk if needed) msdn.microsoft.com/en-us/library/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.