windowswinapimsdn

interface type for a drive letter


Any suggestions on getting the device interface type for a volume, given its drive letter (e.g. G:)? Specifically, am looking for a solution that doesn't depend on WMI.

Thank you.


Solution

  • You can use GetDriveType to get the basic interface type(ie: removable device, CDROM, RAMDisk) for the drive letter, also see the final comment at the bottom of that page for a little more info on removable devices. Also check out SetupDiGetDeviceRegistryProperty and DeviceIoControl

    Her is the best example I can come up with(untested as I don't have the WDK/DDK)

    bool IsUSBDevice(const char* szDrivePath, bool& bRemovable)
    {
        if(GetDriveType(szDrivePath) != DRIVE_REMOVABLE)
            return false;
            
        HANDLE hDevice = CreateFile(szDrivePath,0,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
        if(hDevice == INVALID_HANDLE_VALUE)
            return false;
    
        STORAGE_PROPERTY_QUERY pQuery = {0};
        pQuery.PropertyId = StorageDeviceProperty;
        pQuery.QueryType = PropertyStandardQuery;
    
        STORAGE_DEVICE_DESCRIPTOR pDeviceDesc = {0};
        pDeviceDesc.Size = sizeof(pDeviceDesc);
        DWORD dwWritten = 0;
        if(DeviceIoControl(hDevice,IOCTL_STORAGE_QUERY_PROPERTY,&pQuery,sizeof(STORAGE_PROPERTY_QUERY),pDeviceDesc,sizeof(pDeviceDesc),&dwWritten,NULL))
        {
            CloseHandle(hDevice);
            return ((bRemovable = pDeviceDesc.RemovableMedia) && pDeviceDesc.BusType == BusTypeUsb);
        }
        else
            CloseHandle(hDevice);
               
        return false; 
    }