Cannot override more than 104KB of the MBR in Windows with C#

2

I was trying to override the MBR of my hard drive with an image. I wrote a C# program to do just that, and it worked, but it doesn't allow me to override more than ~104KB of the hard drive. The important data on this image was smaller that that, so everything got copied over successfully, but it still makes no sense to me. If Windows allows me to override the Master Boot Record with whatever I want, why does it not allow me to override more than 104KB? I'm testing it on Windows 10(installed in legacy BIOS mode on VirtualBox).

Here is the code I used

private const uint GenericAll = 0x10000000;
private const uint FileShareRead = 0x1;
private const uint FileShareWrite = 0x2;
private const uint OpenExisting = 0x3;        

public static void OverrideMBR()
        {

            var mbr = CreateFile(
                "\\\\.\\PhysicalDrive0",
                GenericAll,
                FileShareRead | FileShareWrite,
                IntPtr.Zero,
                OpenExisting,
                0,
                IntPtr.Zero);

            if (mbr == (IntPtr)(-0x1))
            {
                Console.WriteLine("Fail: Please run this as an administrator");
                return false;
            }
            uint filesize = 0150000u;
            uint sizeRemaining = filesize;
            byte[] imageFile = new byte[filesize];
            /*Here is the image definition*/
            uint overriden = 0;
            while (sizeRemaining > 0)
            {
                uint towrite = 512;
                if (WriteFile(
                mbr,
                imageFile,
                towrite,
                out uint lpNumberOfBytesWritten,
                IntPtr.Zero))
                {
                    Console.WriteLine("Successfully written 512 bytes");
                }
                else
                {
                    Console.WriteLine("Failed to write 512 bytes. Successfully overriden {0} bytes.", overriden);
                    return;
                }
                sizeRemaining -= lpNumberOfBytesWritten;
                overriden += lpNumberOfBytesWritten;

                byte[] dst = new byte[imageFile.Length - (int)lpNumberOfBytesWritten];
                Array.Copy(imageFile, lpNumberOfBytesWritten, dst, 0, dst.Length);
                imageFile = dst;
            }
            Console.WriteLine("DONE!");
            return;
        }
    }
c#
windows
mbr
asked on Stack Overflow Mar 3, 2020 by Xyz

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0