public static List <int> GetPhysicalDiskIndexList() { List <string> devicePathList = DeviceInterfaceUtils.GetDevicePathList(DeviceInterfaceUtils.DiskClassGuid); List <int> result = new List <int>(); foreach (string devicePath in devicePathList) { SafeFileHandle hDevice = HandleUtils.GetFileHandle(devicePath, FileAccess.Read, ShareMode.ReadWrite); STORAGE_DEVICE_NUMBER number = GetDeviceNumber(hDevice); hDevice.Close(); result.Add((int)number.DeviceNumber); } // We'll now sort the list based on disk number result.Sort(); return(result); }
public static STORAGE_DEVICE_NUMBER GetDeviceNumber(SafeFileHandle hDevice) { uint dummy; STORAGE_DEVICE_NUMBER storageDeviceNumber = new STORAGE_DEVICE_NUMBER(); IntPtr lpOutBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(storageDeviceNumber)); bool success = DeviceIoControl(hDevice, IOCTL_STORAGE_GET_DEVICE_NUMBER, IntPtr.Zero, 0, lpOutBuffer, (uint)Marshal.SizeOf(typeof(STORAGE_DEVICE_NUMBER)), out dummy, IntPtr.Zero); storageDeviceNumber = (STORAGE_DEVICE_NUMBER)Marshal.PtrToStructure(lpOutBuffer, typeof(STORAGE_DEVICE_NUMBER)); Marshal.FreeHGlobal(lpOutBuffer); if (!success) { throw new IOException("Unable to retrieve device number"); } return(storageDeviceNumber); }