WMI
I got to work a bit on Windows Management Instrumentation the other day .....
Well, most people don't know about this so I'll just paste a definition from Wikipedia :P
"Windows Management Instrumentation (WMI) is a set of extensions to the Windows Driver Model that provides an operating system interface through which instrumented components can provide information and notification."
Basically its a set of APIs provided by Microsoft allowing you to monitor and control a lot of administrative aspects of your system.
Most of you have probably interacted with this through the MMC in Control Panel -> Administrative Tools
Before WMI, programmers had to hunt the registry for scraps of information about the system, and if their required information wasn't there, they would have to write low-level assembly to get detailed specs like Processor speed or hard drive volume information.
Now, all this info is exposed through a set of standard classes which is a great plus.
Allright ..... time for the juicy stuff .....
I'll start off by getting processor info from the system.
The first step is to add a reference to a .net assembly called System.Management to your project
Obviously, you would also need to import the same namespace into the class where you need to perform this action.
From here on, the code is pretty straightforward.
public string GetCPUId()
{
string cpuInfo = String.Empty;
string temp=String.Empty;
ManagementClass mc = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach(ManagementObject mo in moc)
{
if(cpuInfo==String.Empty)
{// only return cpuInfo from first CPU
cpuInfo += mo.Properties["ProcessorId"].Value.ToString();
cpuInfo += "\n";
cpuInfo += mo.Properties["Manufacturer"].Value.ToString();
cpuInfo += "\n";
cpuInfo += mo.Properties["Caption"].Value.ToString();
cpuInfo += "\n";
cpuInfo += mo.Properties["MaxClockSpeed"].Value.ToString();
cpuInfo += "\n";
cpuInfo += mo.Properties["L2CacheSize"].Value.ToString();
cpuInfo += "\n";
}
}
return cpuInfo;
}
you can also get other useful information like volume information from the hard drive :
public string GetVolumeSerial(string strDriveLetter)
{
if( strDriveLetter=="" || strDriveLetter==null) strDriveLetter="C";
ManagementObject disk =
new ManagementObject("win32_logicaldisk.deviceid=\"" + strDriveLetter +":\"");
disk.Get();
return disk["VolumeSerialNumber"].ToString();
}
or the MAC address from your Network card :
public string GetMACAddress()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
string MACAddress=String.Empty;
foreach(ManagementObject mo in moc)
{
if(MACAddress==String.Empty) // only return MAC Address from first card
{
if((bool)mo["IPEnabled"] == true) MACAddress= mo["MacAddress"].ToString() ;
}
mo.Dispose();
}
MACAddress=MACAddress.Replace(":","");
return MACAddress;
}
... thats all folks !!!
Have fun !