I’m trying to build a simple Windows Forms application that can query the capabilities of the user’s computer using WMI (starting with the hard drives).
So far, I’ve got this far (HardDriveCheckResult is my own class):
ConnectionOptions wmiConnOpts = new ConnectionOptions();
wmiConnOpts.Impersonation = ImpersonationLevel.Impersonate;
wmiConnOpts.Authentication = AuthenticationLevel.Default;
wmiConnOpts.EnablePrivileges = true;
ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(@"select * from Win32_LogicalDisk WHERE DriveType = 5");
managementObjectSearcher.Scope.Options = wmiConnOpts;
List<HardDriveCheckResult> hardDriveCheckResults = new List<HardDriveCheckResult>();
foreach (ManagementObject managementObject in managementObjectSearcher.Get())
{
string hardDriveName = managementObject["name"].ToString();
object objFreeSpace = managementObject["FreeSpace"];
double freeSpace = objFreeSpace == null ? 0d : (double)objFreeSpace;
... additional code not relevant
}
The issue I’m having is that managementObject["FreeSpace"] always returns null. I suspect this may have something to do with the permissions of the account the WMI call is made with, hence my inclusion of the ConnectionOptions code which comes courtesy of Google.
Task Manager tells me the program is running as my account, which is an administrator, so I’m a bit stumped as to why the WMI calls wouldn’t return all data.
Am I correct that the call to managementObject["FreeSpace"] returns null because of permissions? Or could it be something else entirely?
Oh, the call to managementObject["name"] correctly returns the drive letter by the way.
Okay, the answer is bad Googling. The query is filtering on DriveType = 5, which is CD-ROM drive. I thought I was filtering for hard drives.
The free space part was returning null because there was no disk in the drive.