Search code examples
windowspathdevice

Resolve Windows device path to drive letter


How do you resolve an NT style device path, e.g. \Device\CdRom0, to its logical drive letter, e.g. G:\ ?

Edit: A Volume Name isn't the same as a Device Path so unfortunately GetVolumePathNamesForVolumeName() won't work.


Solution

  • Hopefully the following piece of code will give you enough to solve this - after you've initialised it, you just need to iterate through the collection to find your match. You may want to convert everything to upper/lower case before you insert into the collection to help with lookup performance.

    typedef basic_string<TCHAR> tstring;
    typedef map<tstring, tstring> HardDiskCollection;
    
    void Initialise( HardDiskCollection &_hardDiskCollection )
    {
        TCHAR tszLinkName[MAX_PATH] = { 0 };
        TCHAR tszDevName[MAX_PATH] = { 0 };
        TCHAR tcDrive = 0;
    
        _tcscpy_s( tszLinkName, MAX_PATH, _T("a:") );
        for ( tcDrive = _T('a'); tcDrive < _T('z'); ++tcDrive )
        {
            tszLinkName[0] = tcDrive;
            if ( QueryDosDevice( tszLinkName, tszDevName, MAX_PATH ) )
            {
                _hardDiskCollection.insert( pair<tstring, tstring>( tszLinkName, tszDevName ) );
            }
        }
    }