Thursday, October 9, 2008

How to read disk drive information using C#

I just came across some cool C# code while preparing for the Microsoft 70-536 exam. Using the Windows Management Instrumentation (WMI), you can inspect a machine for available disk drives. Add the System.Management assembly as a reference in your project, and off you go:

ManagementScope DemoScope=new ManagementScope("\\\\enter_machine_name_here\\root\\cimv2");
ObjectQuery DemoQuery = new ObjectQuery("SELECT Size, Name FROM Win32_LogicalDisk WHERE DriveType=3");
ManagementObjectSearcher DemoSearcher = new ManagementObjectSearcher(DemoScope, DemoQuery);
ManagementObjectCollection AllObjects = DemoSearcher.Get();
foreach (ManagementObject DemoObject in AllObjects)
{
Console.WriteLine("Resource Name:" + DemoObject["Name"].ToString());
Console.WriteLine("Resource Size:" + DemoObject["Size"].ToString());
}
Console.Read();

No comments: