Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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();

Monday, January 14, 2008

C# ternary if

Just to get some exposure for pretty specific searches, I wanted to give some examples of the ternary "if" statement in C#: If you would like to set a variable by an "if...else" condition, it can be done with the ternary if statement. (Notice I am also using the new .NET 3.5 "var" to declare my variable). In the example below, I want to see if I am old enough (25 yrs old) to rent a car without the "underage" fee. Is today 25 years or more from my date of birth:
DateTime myBDay = "02/08/1982";
var AmIOldEnough = DateTime.Today >= myBDay.AddYears(25) ? true : false;