Hello,
I am trying to retrieve system information using WMI. Everything is working good until I got to the Hard Drive. I am trying to populate the Drive size for the local Hard Drives on the system. The issue is at runtime it only populate the first drive and does not go beyond that. I am still fairly new to C#. Here is the snippet for the Hard Drive:
public string GetHardDrive()
{
double disk = 0;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_LogicalDisk where DriveType=3");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
disk = Math.Round(((((double)Convert.ToDouble(wmi["Size"]) / 1024) / 1024) / 1024), 2);
return disk.ToString();
}
catch
{
}
}
return "Unable to Find Drive";
}
Any Help would be appreciated.
Thanks in advance.
Loading
Sam HobbsPosted Oct 19, 2010, 5:42 PM
Look at your code. I really doubt that you want to use the return statement there, and I probably don't need to explain what I mean. Do you understand how the return statement causes the problem?
Josh DycusPosted Oct 20, 2010, 9:08 PM
Sam HobbsPosted Oct 20, 2010, 6:53 PM
Josh DycusPosted Oct 20, 2010, 8:29 AM
public string GetHardDrive()
{
double disk = 0;
double free = 0;
StringBuilder Drive = new StringBuilder();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_LogicalDisk Where DriveType = 3");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
disk = Math.Round(((((double)Convert.ToDouble(wmi["Size"]) / 1024) / 1024) / 1024), 2);
free = Math.Round(((((double)Convert.ToDouble(wmi["FreeSpace"]) / 1024) / 1024) / 1024), 2);
Drive.Append("Drive: " + wmi["Name"].ToString() + Environment.NewLine + "Total Size: " +
disk.ToString() + " GB" + Environment.NewLine + "Free Space: " + free.ToString() + " GB"
+ Environment.NewLine + Environment.NewLine);
}
catch (ManagementException ex)
{
MessageBox.Show("There was an error in your Query" + ex.Message.ToString());
}
}
return Drive.ToString();
}
Thanks for all the responses and help I appreciate it.
Mahesh ChandPosted Oct 19, 2010, 8:44 PM
This article gets all drives and lists on the console.
DriveInfo Class in C#
Josh DycusPosted Oct 19, 2010, 8:13 AM
Sam HobbsPosted Oct 18, 2010, 6:24 PM
Try issuing the query using WBEMTest; it is a tool that should be in your system somewhere. When you use it, first click on the Connect button then okay then click on the Query button.