将文件从地址字节复制到地址字节

时间:2018-07-26 08:41:00

标签: c# byte memory-address

我一直在寻找一种将文件的一部分从确定的地址复制到另一个地址的方法,在C#中有没有办法做到这一点?

例如,假设我有一个像这样的文件:

enter image description here

我想从0xA0复制到0xB0,然后将其粘贴到另一个文件中。

2 个答案:

答案 0 :(得分:0)

应该是这样的:

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

答案 1 :(得分:0)

可能是这样的:

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);
相关问题