如何在C++中使用WMI获取硬盘的所有逻辑驱动器的可用空间



我想使用 c++ 和 WMI 计算整个硬盘驱动器的可用空间。

例如。如果 HDD 包含 3 个逻辑驱动器,则表示 C: , D: , E: 每个逻辑驱动器都有以下配置。

驱动器总空间可用空间

C: 10GB 5 GB深:20国标 8国标E:15GB 7 GB

所以我需要获取可用硬盘空间,即所有驱动器 C、D 和 E 的可用空间。

因此,它应该返回 5+8+7 = 20 GB。

我也不知道该硬盘驱动器存在的所有逻辑驱动器。

这是一个完全有效的功能,可让您获得所有驱动器中的可用空间。它将结果生成为 CString,但当然您可以返回一个数字(字节数)。

CString GetFreeDiskSpace()
{
    CString str_result{ L"" };
    DWORD cchBuffer;
    WCHAR stddriveStrings[2048];
    WCHAR *driveSetings = &stddriveStrings[0];
    UINT driveType;
    PWSTR driveTypeString;
    ULARGE_INTEGER freeSpace;
    // Find out the required buffer size that we need
    cchBuffer = GetLogicalDriveStrings(0, NULL);

    // Fetch all drive letters as strings 
    GetLogicalDriveStrings(cchBuffer, driveSetings);
    // Loop until we reach the end (by the '' char)
    // driveStrings is a double null terminated list of null terminated strings)
    while (*driveSetings)
    {
        // Dump drive information
        driveType = GetDriveType(driveSetings);
        GetDiskFreeSpaceEx(driveSetings, &freeSpace, NULL, NULL);
        switch (driveType)
        {
            case DRIVE_FIXED:
                driveTypeString = L"Hard Drive";
                break;
            case DRIVE_CDROM:
                driveTypeString = L"CD/DVD";
                break;
            case DRIVE_REMOVABLE:
                driveTypeString = L"Removable";
                break;
            case DRIVE_REMOTE:
                driveTypeString = L"Network";
                break;
            default:
                driveTypeString = L"Unknown";
                break;
        }
        str_result.Format(L"%sn%s - %s - %I64u GB free", 
            str_result, driveSetings, driveTypeString,
            freeSpace.QuadPart / 1024 / 1024 / 1024);
  // Move to next drive string
  // +1 is to move past the null at the end of the string.
        driveSetings += _tcsclen(driveSetings) + 1;
    }

    return str_result;
}

非 WMI ay 要容易得多。

您可以使用GetLogicalDriveStrings (https://msdn.microsoft.com/en-us/library/windows/desktop/aa364975(v=vs.85).aspx) 获取系统中的所有驱动器。

接下来使用 GetDiskFreeSpace (https://msdn.microsoft.com/en-us/library/windows/desktop/aa364935(v=vs.85).aspx) 查找特定驱动器的可用空间。

如果你真的想(必须)坚持使用WMI,页面 https://msdn.microsoft.com/en-us/library/windows/desktop/aa393244(v=vs.85).aspx将给出一些关于如何实例化WMI类的说明,你将需要使用具有FreeSpace成员的Win32_LogicalDisk(https://msdn.microsoft.com/en-us/library/windows/desktop/aa394173(v=vs.85).aspx)类。

最新更新