1

这是我所拥有的:

public static bool DriveHasLessThanTenPercentFreeSpace(string server)
{
    long driveSize = 0;
    long freeSpace = 0;

    var oConn = new ConnectionOptions {Username = "username", Password = Settings.Default.SQLServerAdminPassword};
    var scope = new ManagementScope("\\\\" + server + "\\root\\CIMV2", oConn);
    scope.Connect();

    var query = new ObjectQuery("SELECT FreeSpace FROM Win32_LogicalDisk where DeviceID = 'D:'");

    var searcher = new ManagementObjectSearcher(scope, query);
    ManagementObjectCollection queryCollection = searcher.Get();
    foreach (ManagementObject m in queryCollection)
    {
        //the FreeSpace value is in bytes
        freeSpace = Convert.ToInt64(m["FreeSpace"]);

        //error happens here!
        driveSize = Convert.ToInt64(m["Size"]);
    }

    long percentFree = ((freeSpace / driveSize) * 100);
    if (percentFree < 10)
    {
        return true;
    }
    return false;
}

这行代码给了我一个错误:

driveSize = Convert.ToInt64(m["Size"]);

错误说:

ManagementException was unhandled by user code

未找到

我假设获取驱动器大小的查询是错误的。

请注意,我在以下行获得了 freeSpace 值:

freeSpace = Convert.ToInt64(m["FreeSpace"]);

所以我知道该查询适用于 freeSpace。

谁能帮我一把?

4

1 回答 1

2

它需要SELECT * FROM Win32_LogicalDisk...在您的查询中。

因为您在查询中选择“FreeSpace”,除了可用空间将被返回,其他一切都会抛出异常。

如果您不想返回所有内容(因为它是远程查询),您有几个选择:

  • 我不确定管理层是否允许您只选择两个项目?我不熟悉语法。不过你可以试试SELECT FreeSpace, Size FROM Win32_LogicalDisk...
  • If not, you could simply do two queries, one for the freespace, and one for the size.
于 2012-11-15T17:03:07.567 回答