Querying the size of a drive on a remote server is giving me an error
- by Testifier
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);
//connect to the scope
scope.Connect();
//construct the query
var query = new ObjectQuery("SELECT FreeSpace FROM Win32_LogicalDisk where DeviceID = 'D:'");
//this class retrieves the collection of objects returned by the query
var searcher = new ManagementObjectSearcher(scope, query);
//this is similar to using a data adapter to fill a data set - use an instance of the ManagementObjectSearcher to get the collection from the query and store it
ManagementObjectCollection queryCollection = searcher.Get();
//iterate through the object collection and get what you're looking for - in my case I want the FreeSpace of the D drive
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?