'Get list of USB devices in windows

I am attempting to get a list of removable/USB drives connected to a Windows computer. I have tried functions like GetLogicalDrives however I have had no luck. I am looking for an effective method of gathering the USB list



Solution 1:[1]

This will do what you asked. It returns all removable drives, meaning that it will returns all USB drives, but also everything tagged as "Removable" by Windows - excepted CD-ROM, they have their own type (see GetDriveType for details).

If you want exclusively USB drives, you'll need to call also SetupDiGetDeviceRegistryPropertyW with SPDRP_REMOVAL_POLICY property before accepting the drive, I've left a comment to where you should insert it if needed.

#include <Windows.h>
#include <fileapi.h>
#include <tchar.h>

// Return a list of removable devices like GetLogicalDrives
// Bit 0=drive A, bit 26=drive Z.
// 1=removable drive, 0=everything else.
DWORD getRemovableDrives()
{
    DWORD result = 0u ;
    DWORD curr = 0u ;
    // Found all existing drives.
    if ((curr=GetLogicalDrives())) {
        TCHAR root[3] = TEXT("A:") ;
        int idx = 1 ;
        // Parse drives.
        for (int i=0;i<26;i++, idx<<=1) {
            // If drive present, check it..
            if ( (curr & idx) && (GetDriveType(root)==DRIVE_REMOVABLE) )
                // Drive is removable (can be USB, CompactFlash, SDCard, ...).
                // Call SetupDiGetDeviceRegistryPropertyW here if needed.
                result |= idx ;
            root[0]++ ;
        }
    }
    return result ;
}

int main()
{
    DWORD removableDrives = getRemovableDrives() ;
    int count = 0 ;
    _tprintf(TEXT("Current removable drive(s):\n\t")) ;
    for (int i=0 ; i<26 ; i++)
        if (removableDrives & (1<<i)) {
            _tprintf(TEXT("%c: "),_T('A')+i) ;
            count++ ;
        }
    _tprintf(TEXT("\nFound %d removable drive(s).\n"),count) ;
    return 0 ;
}

Sample output:

Current removable drive(s):
    K: N: 
Found 2 removable drive(s).

The main function, getRemovableDrives(), is obviously fully silent and does not produce any output. The main() only shows how to parse its results. The function is pretty fast, therefore you can call it without impacting too much performances - but it would be better to get notifications about drives connection/disconnection anyway.

Error checking is at minimal level, and my Unicode C is a bit rusted so they may be some space for some little more optimizations.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wisblade