0

Using C#, how do I backup the Windows Master Boot Record of the system booted hard drive? It's for an Antivirus engine.

Volomike
  • 23,743
  • 21
  • 113
  • 209

1 Answers1

1
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace BackupMBR
{
    class Program
    {

        [DllImport("kernel32")]
        private static extern IntPtr CreateFile(
           string lpFileName,
           uint dwDesiredAccess,
           uint dwShareMode,
           IntPtr lpSecurityAttributes,
           uint dwCreationDisposition,
           uint dwFlagsAndAttributes,
           IntPtr hTemplateFile);

        static void Main(string[] args)
        {
            IntPtr handle = CreateFile(
                @"\\.\PHYSICALDRIVE0",
                0x80000000, 
                1, 
                IntPtr.Zero, 
                3, 
                0, 
                IntPtr.Zero
           );
            using (FileStream disk = new FileStream(handle, FileAccess.Read))
            {
                byte[] mbrData = new byte[512];
                Console.WriteLine("Starting MBR Backup...");
                try
                {
                    disk.Read(mbrData, 0, mbrData.Length);
                    FileStream mbrSave = new FileStream("mbr.img", FileMode.Create);
                    mbrSave.Write(mbrData, 0, mbrData.Length);
                    Console.WriteLine("MBR Backuped to mymbr.img success!");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            Console.ReadKey();

        }
    }
}
Volomike
  • 23,743
  • 21
  • 113
  • 209
  • Nice clear code, but what about GPTs? – Dave Burton Oct 08 '17 at 03:54
  • 1
    @DaveBurton Good point. I'm reviewing [this doc](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363785(v=vs.85).aspx#partition_styles) from Microsoft to learn more. – Volomike Oct 09 '17 at 21:53