本质上和VC 写的没有区别,都是使用 CreateFile 打开 PhysicalDrive 然后进行操作。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
namespace RW_PyhsicalDisk
{
class Program
{
[DllImport("kernel32", SetLastError = true)]
static extern IntPtr CreateFile(
string FileName,
uint DesiredAccess,
uint ShareMode,
IntPtr SecurityAttributes,
uint CreationDisposition,
int FlagsAndAttributes,
IntPtr hTemplate
);
static class DESIREDACCESS
{
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint GENERIC_EXECUTE = 0x20000000;
public const uint GENERIC_ALL = 0x10000000;
}
/// <summary>
/// Sharing mode of the file or object
///</summary>
static class SHAREMODE
{
public const uint FILE_SHARE_READ = 0x00000001;
public const uint FILE_SHARE_WRITE = 0x00000002;
public const uint FILE_SHARE_DELETE = 0x00000004;
}
/// <summary>
/// Action to take on files that exist, and which action to take when files do not exist.
/// </summary>
static class CREATIONDISPOSITION
{
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
public const uint OPEN_ALWAYS = 4;
public const uint TRUNCATE_EXISTING = 5;
}
/// <summary>
/// File attributes and flags for the file.
/// </summary>
static class FLAGSANDATTRIBUTES
{
public const uint FILE_FLAG_WRITE_THROUGH = 0x80000000;
public const uint FILE_FLAG_OVERLAPPED = 0x40000000;
public const uint FILE_FLAG_NO_BUFFERING = 0x20000000;
public const uint FILE_FLAG_RANDOM_ACCESS = 0x10000000;
public const uint FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000;
public const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;
public const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
public const uint FILE_FLAG_POSIX_SEMANTICS = 0x01000000;
public const uint FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;
public const uint FILE_FLAG_OPEN_NO_RECALL = 0x00100000;
public const uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
}
static void Main(string[] args)
{
IntPtr handle = CreateFile(@"\\.\PHYSICALDRIVE1",
DESIREDACCESS.GENERIC_READ | DESIREDACCESS.GENERIC_WRITE,
SHAREMODE.FILE_SHARE_READ | SHAREMODE.FILE_SHARE_WRITE,
IntPtr.Zero,
CREATIONDISPOSITION.OPEN_EXISTING,
0,
IntPtr.Zero);
FileStream disk = new FileStream(handle, FileAccess.ReadWrite);
byte[] bt = new byte[512];
disk.Seek(0, SeekOrigin.Begin);
disk.Read(bt, 0, 512);
for (int i = 0; i < bt.Length; i++)
{
Console.Write(bt[i].ToString("x2") + " ");
}
Console.ReadLine();
}
}
}
运行结果: