0
votes

Context : My application writes data in USB ,CD & DVD. I am using RegisterDeviceNotification for detect device changes.To ensure that connected device is USB based storage device i am using DeviceIoControl api.

Problem : Now i need to identify Storage devices in USB devices. During testing i found USB based CD/DVD were also detected by logic as USB mass storage device. I added check for Device Type. But i don't see any device type in SCSI for USB mass storage.

Please suggest me a good solution to uniquely identify a USB Mass storage device.

 bool IsUsbStorageDevice( wchar_t letter )
    {
        wchar_t volumeAccessPath[] = L"\\\\.\\X:";
        volumeAccessPath[4] = letter;

        HANDLE deviceHandle = CreateFileW(
            volumeAccessPath,
            0,                // no access to the drive
            FILE_SHARE_READ | // share mode
            FILE_SHARE_WRITE,
            NULL,             // default security attributes
            OPEN_EXISTING,    // disposition
            0,                // file attributes
            NULL);            // do not copy file attributes

        // setup query
        STORAGE_PROPERTY_QUERY query;
        memset(&query, 0, sizeof(query));
        query.PropertyId = StorageDeviceProperty;
        query.QueryType = PropertyStandardQuery;

        // issue query
        DWORD bytes;
        STORAGE_DEVICE_DESCRIPTOR devd;
        STORAGE_BUS_TYPE busType = BusTypeUnknown;
        bool usbcdrom = false;

        if (DeviceIoControl(deviceHandle,
            IOCTL_STORAGE_QUERY_PROPERTY,
            &query, sizeof(query),
            &devd, sizeof(devd),
            &bytes, NULL))
        {
            busType = devd.BusType;
            usbcdrom = devd.DeviceType == 0x005;
        }
        CloseHandle(deviceHandle);
        return (BusTypeUsb == busType) && !usbcdrom;
    }
2

2 Answers

0
votes

You must use L"\\\\.\\PhysicalDriveN" instead of L"\\\\.\\X:"

where you change N from 0 to 29:

PhysicalDrive0

PhysicalDrive1

...

PhysicalDrive29

0
votes

GetDriveType(root) delivers the drive type, as removeable, fixed, cdrom and some others:

wchar_t rootPath[] = L"X:\\";
rootPath[0] = letter;

DWORD DriveType = GetDriveType( rootPath );

switch ( DriveType ) {
    case DRIVE_CDROM:
        // CD/DVD/BR drive
        break;
    case DRIVE_REMOVABLE:
        // most flash drives, card readers
        break;
    case DRIVE_FIXED:
        // some flash drives, hard drives
        break;
    default:
        // never seen for USB drives
        break;
}