[StructLayout(LayoutKind.Sequential)]
struct STORAGE_DEVICE_NUMBER
{
public int DeviceType;
public int DeviceNumber;
public int PartitionNumber;
}
Structure STORAGE_DEVICE_NUMBER
Public TODO
End Structure
None.
When used with a drive letter, the path should not have a trailing backslash ("\\.\C:")
// return a unique device number for the given device path
int GetDeviceNumber(string DevicePath)
{
int ans = -1;
IntPtr h = CreateFile(DevicePath.TrimEnd('\\'), 0, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (h.ToInt32() != INVALID_HANDLE_VALUE)
{
int requiredSize;
STORAGE_DEVICE_NUMBER Sdn = new STORAGE_DEVICE_NUMBER();
int nBytes = Marshal.SizeOf(Sdn);
IntPtr ptrSdn = Marshal.AllocHGlobal(nBytes);
if (DeviceIoControl(h, IOCTL_STORAGE_GET_DEVICE_NUMBER, IntPtr.Zero, 0, ptrSdn, nBytes, out requiredSize, IntPtr.Zero))
{
Sdn = (STORAGE_DEVICE_NUMBER)Marshal.PtrToStructure(ptrSdn, typeof(STORAGE_DEVICE_NUMBER));
// just my way of combining the relevant parts of the
// STORAGE_DEVICE_NUMBER into a single number
ans = (Sdn.DeviceType << 8) + Sdn.DeviceNumber;
}
Marshal.FreeHGlobal(ptrSdn);
CloseHandle(h);
}
return ans;
}