internal static int CheckDriveType(string name) { int retVal = 0; int bytesReaded = 0; IntPtr handle; string nameNoSlash = name.Substring(0, name.Length - 1); var driveType = NativeDisk.GetDriveType(name); switch (driveType) { case DriveType.Fixed: case DriveType.Removable: handle = NativeDisk.CreateFile(nameNoSlash, NativeDisk.FILE_READ_ATTRIBUTES, NativeDisk.FILE_SHARE_READ | NativeDisk.FILE_SHARE_WRITE, IntPtr.Zero, NativeDisk.OPEN_EXISTING, 0, IntPtr.Zero); if (handle == NativeDisk.INVALID_HANDLE_VALUE) { var exception = new Win32Exception(Marshal.GetLastWin32Error()); throw new Exception(string.Format("Error occured when trying to check drive type 1.\nError code: {0}\nMessage: {1}", exception.NativeErrorCode, exception.Message)); } else { STORAGE_DEVICE_DESCRIPTOR devDescriptor = new STORAGE_DEVICE_DESCRIPTOR(); STORAGE_DEVICE_NUMBER devNumber = GetDiskProperty(handle, ref devDescriptor); if ((driveType == DriveType.Removable && devDescriptor.BusType != STORAGE_BUS_TYPE.BusTypeSata) || (driveType == DriveType.Fixed && devDescriptor.BusType == STORAGE_BUS_TYPE.BusTypeUsb) || (devDescriptor.BusType == STORAGE_BUS_TYPE.BusTypeSd) || (devDescriptor.BusType == STORAGE_BUS_TYPE.BusTypeMmc)) { if (NativeDisk.DeviceIoControl(handle, NativeDisk.IOCTL_STORAGE_CHECK_VERIFY2, IntPtr.Zero, 0, IntPtr.Zero, 0, ref bytesReaded, IntPtr.Zero)) { retVal = devNumber.DeviceNumber; } else { NativeDisk.CloseHandle(handle); Utils.SetErrorMode(Utils.ErrorModes.SEM_FAILCRITICALERRORS); try { handle = NativeDisk.CreateFile(name, NativeDisk.FILE_READ_DATA, NativeDisk.FILE_SHARE_READ | NativeDisk.FILE_SHARE_WRITE, IntPtr.Zero, NativeDisk.OPEN_EXISTING, 0, IntPtr.Zero); } finally { Utils.SetErrorMode(Utils.ErrorModes.SYSTEM_DEFAULT); } if (handle == NativeDisk.INVALID_HANDLE_VALUE) { var exception = new Win32Exception(Marshal.GetLastWin32Error()); throw new Exception(string.Format("Error occured when trying to check drive type 2.\nError code: {0}\nMessage: {1}", exception.NativeErrorCode, exception.Message)); } if (NativeDisk.DeviceIoControl(handle, NativeDisk.IOCTL_STORAGE_CHECK_VERIFY, IntPtr.Zero, 0, IntPtr.Zero, 0, ref bytesReaded, IntPtr.Zero)) { retVal = devNumber.DeviceNumber; } } } NativeDisk.CloseHandle(handle); } break; default: throw new Win32Exception("Invalid device type"); } return(retVal); }