0

I was looking around for a way to copy a portion of a file from a determined address to another address, is there a way to do that in C#?

For example let's say i have a file like this:

enter image description here

and I want to copy from 0xA0 to 0xB0 and then paste it to another file.

FabioEnne
  • 732
  • 1
  • 14
  • 43

2 Answers2

0

It should be something like:

// input data
string inputName = "input.bin";
long startInput = 0xa0;
long endInput = 0xb0; // excluding 0xb0 that is not copied
string outputName = "output.bin";
long startOutput = 0xa0;

// begin of code
long count = endInput - startInput;

using (var fs = File.OpenRead(inputName))
using (var fs2 = File.OpenWrite(outputName))
{
    fs.Seek(startInput, SeekOrigin.Begin);
    fs2.Seek(startOutput, SeekOrigin.Begin);

    byte[] buf = new byte[4096];

    while (count > 0)
    {
        int read = fs.Read(buf, 0, (int)Math.Min(buf.Length, count));

        if (read == 0)
        {
            // end of file encountered
            throw new IOException("end of file encountered");
        }

        fs2.Write(buf, 0, read);

        count -= read;
    }
}
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • `throw new Exception();` - something (I'll never tell you what!) went wrong - if you throw exception, please, be specific: at least `throw new IOException("End of file encountered");` – Dmitry Bychenko Jul 26 '18 at 09:04
  • @DmitryBychenko My laziness in exception throwing is legendary :-) – xanatos Jul 26 '18 at 09:06
0

Something like this perhaps:

long start = 0xA0;
int length = 0xB0 - start;            
byte[] data = new byte[length];

using (FileStream fs = File.OpenRead(@"C:\Temp\InputFile.txt"))
{
    fs.Seek(start, SeekOrigin.Begin);
    fs.Read(data, 0, length);
}

File.WriteAllBytes(@"C:\Temp\OutputFile.txt", data);
Cosmin
  • 2,365
  • 2
  • 23
  • 29