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?
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:
SELECT FreeSpace, Size FROM Win32_LogicalDisk...