C#读磁盘扇区
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
namespace SDCardRead
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public const short FILE_ATTRIBUTE_NORMAL = 0x80;
public const short INVALID_HANDLE_VALUE = -1;
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
public const uint FILE_BEGIN = 0;
public const uint FILE_CURRENT = 1;
public const uint FILE_END = 2;
[DllImport("Kernel32.dll")]
extern static IntPtr CreateFile(string fileName, uint accessFlag, uint shareMode, IntPtr security,
uint createFlag, uint attributeFlag, IntPtr tempfile);
[DllImport("Kernel32.dll")]
extern static bool ReadFile(IntPtr handle, [Out] byte[] buffer, uint bufferLength,
ref uint length, IntPtr overLapped);
[DllImport("Kernel32.dll")]
extern static bool CloseHandle(IntPtr handle);
[DllImport("Kernel32.dll")]
extern static uint SetFilePointer(IntPtr handle, uint offset, IntPtr distance, uint flag);
/// <summary>
/// Read Disk MBR(Main Boot Record)
/// </summary>
/// <returns>512 byte for MBR record</returns>
public static byte[] ReadMBR(uint SectorIndex)
{
const string SD_CARD_PATH = @"\\.\G:"; // X: 替换为你的SD卡驱动器字母
IntPtr DiskHandle = CreateFile(
SD_CARD_PATH,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
IntPtr.Zero,
OPEN_EXISTING,
0,
IntPtr.Zero);
byte[] buffer = new byte[512];
uint length = 0;
SetFilePointer(DiskHandle, SectorIndex, IntPtr.Zero, FILE_BEGIN);
ReadFile(DiskHandle, buffer,(uint) buffer.Length, ref length, IntPtr.Zero);
CloseHandle(DiskHandle);
return buffer;
}
}
}