c#直接读写物理硬盘引导区
其实读写硬盘引导区和是不是c#没有关系,只要能用windows api的语言都可以。
原理就是用createfile这个api,获得物理硬盘的handle,然后用FileStream读取就可以了,FileStream有几个构造函数是以句柄方式初始化的。
\\.\PHYSICALDRIVE0 就是第一个物理硬盘了,其他的就是1、2、3……
- using System;
- using System.IO;
- using System.Runtime.InteropServices;
- namespace test
- {
- class test
- {
- [DllImport("kernel32", SetLastError = true)]
- static extern IntPtr CreateFile(
- string FileName,
- FileAccess DesiredAccess,
- FileShare ShareMode,
- IntPtr SecurityAttributes,
- FileMode CreationDisposition,
- int FlagsAndAttributes,
- IntPtr hTemplate
- );
- public const int FILE_FLAG_NO_BUFFERING = 0x20000000;
- public static void Main()
- {
- IntPtr handle = CreateFile(@"\\.\PHYSICALDRIVE0", FileAccess.Read, FileShare.None, IntPtr.Zero, FileMode.Open, FILE_FLAG_NO_BUFFERING, IntPtr.Zero);
- FileStream disk = new FileStream(handle, FileAccess.Read);
- byte[] outBuffer = new byte[512];
- byte[] inBuffer = new byte[512];
- outBuffer[0] = 1;
- outBuffer[1] = 0;
- outBuffer[2] = 1;
- disk.Seek(0, SeekOrigin.Begin);
- for (int i = 0; i < 512; i++)
- {
- inBuffer[i] = (byte)disk.ReadByte();
- }
- for (int i = 0; i < 512; i++)
- {
- Console.Write(inBuffer[i].ToString("x2")+" ");
- }
- Console.Read();
- }
- }
- }
当然不只是可以读取引导区,整个硬盘都可以啊。
另外,既然获得了硬盘的FileStream了,那么就不止可以Read了,当然也可以Write了,不过FileAccess什么的就得改改了。
干脆把改写的也贴上吧,我在虚拟机里实验的,运行后就这样了,没敢在真机试,有兴趣的同学可以在真机运行一下以下代码。
- using System;
- using System.IO;
- using System.Runtime.InteropServices;
- namespace test
- {
- class test
- {
- [DllImport("kernel32", SetLastError = true)]
- static extern IntPtr CreateFile(
- string FileName,
- uint DesiredAccess,
- uint ShareMode,
- IntPtr SecurityAttributes,
- uint CreationDisposition,
- int FlagsAndAttributes,
- IntPtr hTemplate
- );
- public const int FILE_FLAG_NO_BUFFERING = 0x20000000;
- public static void Main()
- {
- IntPtr handle = CreateFile(@"\\.\PHYSICALDRIVE0", 0x40000000|0x80000000, 0 , IntPtr.Zero, 3, FILE_FLAG_NO_BUFFERING, IntPtr.Zero);
- Console.WriteLine(handle.ToString());
- FileStream disk = new FileStream(handle,FileAccess.ReadWrite);
- byte[] bt = new byte[512];
- Random rnd = new Random();
- rnd.NextBytes(bt);
- for (int i = 0; i < bt.Length; i++)
- {
- Console.Write(bt[i].ToString("x2") + " ");
- }
- disk.Seek(0, SeekOrigin.Begin);
- try
- {
- disk.Write(bt, 0, 512);
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- }
- }
- }
- }