Page 1 of 1

[MFC] Cum enumar drive-urile din sistem?

Posted: 06 Aug 2009, 14:36
by Ovidiu Cucu
Intrebare: Cum enumar drive-urile din sistem (partitii, discuri, drive-uri de retea, etc)?

Raspuns: Exista doua functii cu care se poate face aceasta: GetLogicalDrives si GetLogicalDriveStrings.

Exemple:

Folosind GetLogicalDrives intorc lista de drive-uri intr-un array de char-uri.

Code: Select all

INT_PTR CDrives::EnumLogicalDrives(CArray<TCHAR, TCHAR>& arrDrives) 
{ 
   arrDrives.RemoveAll(); 

    const DWORD dwDrivesMask = ::GetLogicalDrives(); 
    const DWORD dwMaxDrives = 26; 

    for(DWORD dwBit = 0; dwBit < dwMaxDrives; dwBit++) 
    { 
        if(dwDrivesMask & (1 << dwBit)) 
        { 
            TCHAR chDrive = 'A' + static_cast<TCHAR>(dwBit);
            arrDrives.Add(chDrive); 
        } 
    }
    return arrDrives.GetSize();
}
Folosind GetLogicalDriveStrings intorc lista de drive-uri intr-un array de string-uri:

Code: Select all

INT_PTR CDrives::EnumLogicalDrives(CStringArray& arrDrives) 
{ 
    arrDrives.RemoveAll(); 
    CString strDrives;

    const DWORD nBufferLength = 105; // 26 * 4  +  1 
    LPTSTR lpDrive = strDrives.GetBufferSetLength(nBufferLength);
    ::GetLogicalDriveStrings(nBufferLength, lpDrive); 
    while(*lpDrive) 
    {
        CString strDrive = lpDrive;
        arrDrives.Add(strDrive); 
        lpDrive += strDrive.GetLength() + 1; 
    }
    strDrives.ReleaseBuffer();
    return arrDrives.GetSize();
}
Umplem un listbox cu rezultatul intors de EnumLogicalDrives

Code: Select all

void CDrives::FillListBox(CListBox& listBox)
{
    listBox.ResetContent();
    CStringArray arrDrives;
    const INT_PTR nCount = EnumLogicalDrives(arrDrives);
    for(INT_PTR nIndex = 0; nIndex < nCount; nIndex++)
    {
        const CString& strDrive = arrDrives.ElementAt(nIndex);
        listBox.AddString(strDrive);
    }
}
Vezi si: << Back to MFC index