Querying the size of a drive on a remote server is

2019-08-04 03:14发布

Here's what I have:

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;
}

This line of code is giving me an error:

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

The error says:

ManagementException was unhandled by user code

Not found

I'm assuming the query to get the drive size is wrong.

Please note that I AM getting the freeSpace value at the line:

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

So I know the query IS working for freeSpace.

Can anyone give me a hand?

标签: c# .net wmi
1条回答
做个烂人
2楼-- · 2019-08-04 03:35

It needs to be SELECT * FROM Win32_LogicalDisk... in your query.

Because you are selecting "FreeSpace" in your query nothing else but the free space will be returned, and everything else will throw an exception.

In the case you dont want to return everything (because its a remote query) you have a couple options:

  • I'm not sure if management will allow you to select only two items? I'm not familiar with the syntax. However you could try SELECT FreeSpace, Size FROM Win32_LogicalDisk...
  • If not, you could simply do two queries, one for the freespace, and one for the size.
查看更多
登录 后发表回答