【问题标题】:How Do I Backup the Windows Master Boot Record with C#? [closed]如何使用 C# 备份 Windows 主引导记录? [关闭]
【发布时间】:2018-03-17 15:24:40
【问题描述】:

使用 C#,如何备份系统启动硬盘的 Windows 主启动记录?它用于防病毒引擎。

【问题讨论】:

    标签: c# .net disk hard-drive mbr


    【解决方案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();
    
            }
        }
    }
    

    【讨论】:

    • 不错的清晰代码,但 GPT 呢?
    • @DaveBurton 好点。我正在查看来自 Microsoft 的 this doc 以了解更多信息。
    猜你喜欢
    • 2023-03-20
    • 2017-06-15
    • 2021-06-30
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 2018-12-11
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多