Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

An introduction in retrieving WMI in C#

This is a short introduction into retrieving WMI information using hard drive serial and model numbers as an example.

On Thursday, July 8th 2004 at 04:39 AM
By Andy Jump (View Profile)
*****   (Rated 4.4 with 25 votes)
Contextual Ads
More C# Resources
Advertisement

An introduction in retrieving WMI in C#.

C#

Freeware

English

This is a short introduction into retrieving WMI information using hard drive serial and model numbers as an example.


Windows Management Instrumentation (WMI)

WMI is a very useful way of accessing a huge amount of data about your hardware and software on a windows PC. It has been included to varying degrees in every Microsoft OS since Windows 95.

In Microsoft’s own words:

Managing with WMI
Windows Management Instrumentation (WMI) is based on the Web-Based Enterprise Management (WBEM) initiative. Industry leaders formed the WBEM initiative to produce a framework for standardized, low-cost solutions to enterprise system management needs.
The purpose of WMI is to provide a standardized means for managing your computer system, be it a local computer or all the computers in an enterprise. In its simplest terms, management is little more than the collecting data about the state of a managed object on the computer system and altering the state of the managed object by changing the data stored about the object. A managed object can be a hardware entity, such as a memory array, port, or disk drive. It can also be a software entity, such as a service, user account, or page file.
WMI can manage the many components of a computer system. In managing a hard disk, you can use WMI to monitor the amount of free space remaining on the disk. You could also use WMI to remotely alter the state of the drive by deleting files, changing file security, or partitioning or formatting the drive. Using the WMI framework, you can create a management application that monitors an enterprise, provides event-based alerts, and allows a user to control different aspects of an enterprise.

The Code:

A great place to start with C# is always the using statements and any reference’s you need to make, so here they are:

You will need to add System.Managment as a reference (right click the references folder under your solution in VS and select System.Managment under the .NET tab).


using System;
using System.Collections;
using System.Management;



The collections will be used to gather information about multiple hard drives on a system and management will of course access the WMI ;)

Normally a struct would be used to contain the information about the hard drive but due to some issues I had that are beyond the scope of this article I have used a normal class to contain the information.


class HardDriveInfo
{
    private string modelNo = null;
    private string serialNo = null;
    private string type = null;

    public string ModelNo
    {
        get 
        {
            return modelNo;
        }
        set 
        {
            modelNo = value;
        }
    }
    public string SerialNo
    {
        get 
        {
            return serialNo;
        }
        set 
        {
            serialNo = value;
        }
    }
    public string Type
    {
        get 
        {
            return type;
        }
        set
        {
            type = value;
        }
    }
}



This class provides us with a convenient way to store and access all the information we have about a hard drive.

Now on to the main class:


class TestProgram
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        
        [STAThread]
        static void Main(string[] args)
        {



This is your usual boring entry point. For this example I’m just making a quick Console Application that will write the information to the console, it should be easy enough for you to port it over into a workable class.


            ArrayList AL_HardDrives = new ArrayList();

            ManagementObjectSearcher MOS_HDSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");



The AL_HardDrives is the array list that we will store the information about the hard drives in. The Management Object Searcher access the WMI information, it uses SQL query’s to obtain the appropriate information. As previously mentioned the WMI has a vast amount of information accessible from it, far too much to list here but at the end of this article I will provide some links to helpful resources.


            foreach(ManagementObject MO_HD in MOS_HDSearcher.Get())
            {
                HardDriveInfo HDI = new HardDriveInfo();
                HDI.ModelNo    = MO_HD["Model"].ToString();
                HDI.Type        = MO_HD["InterfaceType"].ToString();

                AL_HardDrives.Add(HDI);
            }



The MOS_HDSearcher will return information about multiple hard drives if more than one is installed in a PC when the Get method is called. We need to retrieve each one of these separately so we get each Management Object separately and parse out the information in it to our hard drive class.


            MOS_HDSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");

            int i = 0;
            foreach(ManagementObject MO_HD in MOS_HDSearcher.Get())
            {
                HardDriveInfo HDI = (HardDriveInfo)AL_HardDrives[i];

                if (MO_HD["SerialNumber"] == null)
                    HDI.SerialNo = "None";
                else
                    HDI.SerialNo = MO_HD["SerialNumber"].ToString();
                ++i;
            }



"SELECT * FROM Win32_DiskDrive" only returns the model number and the interface type of the hard drive so we need to reprogram the MOS_HDSearcher with the "SELECT * FROM Win32_PhysicalMedia" query to retrieve the serial number and parse it into the appropriate hard drive information.


            foreach(HardDriveInfo hd in AL_HardDrives)
            {
                Console.WriteLine("Model\t\t: " + hd.ModelNo);
                Console.WriteLine("Type\t\t: " + hd.Type);
                Console.WriteLine("Serial No.\t: " + hd.SerialNo);
                Console.WriteLine();
            }

            Console.ReadLine();
        }
}


Finally we want to display the information about the hard drives and wait for the user to hit enter before closing. Don’t forget to put these two classes into a namespace as well.

So there you are, your very own little program to get hold of the information about a hard drive and the basis for getting any information from the WMI.

Practical Applications

The hard drive serial number is very useful for tying applications to a specific pc within licensing and activation code. The WMI has so much information in it that the uses for it are almost limitless from performance monitors to hardware detection and registry editors.


The major source for WMI information can be found at:
MSDN WMI
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Chandramohan on Tuesday, July 27th 2004 at 02:24 AM

I want to retrieve the serial no, model no, and type of a processor using c#

by Andrei Pociu on Tuesday, July 27th 2004 at 03:26 AM

Here's how:

http://www.eggheadcafe.com/articles/20030511.asp

by Andy Jump on Tuesday, July 27th 2004 at 03:47 AM

hmmm the link to the msn seems duff ... here it is in plain text:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/wmi_start_page.asp

Here is the page with all the info about the processor:

http://msdn.microsoft.com/library/en-us/wmisdk/wmi/win32_processor.asp?frame=true

just swap that out for the hdd info in the above code and you'll be sorted :)

by jok3r on Sunday, October 3rd 2004 at 02:59 PM

and how about the motherboard id ? because i didn't find it on the net for c++/c# but only for delphi.
help me please, because i don't figure out how the classes work ...

by Andy Jump on Monday, October 4th 2004 at 01:50 PM

If you look under the msdn link i gave in the post above there a section called WMI Reference on the left side bar, then click
WMI Classes
WIN32 Classes
Computer System Hardware Classes
WIN32_MotherboardDevice

that will display all the reference material for retiving the motherboard info. All you need to do is create the appropriate struct, change the info retival strings and loops and out will pop the info you need :)

At some point I will sit down and write down all that is needed to access all the WMI info easily but that will be a full componant for sale on our site.

by swapnil on Thursday, February 24th 2005 at 07:32 AM

i want to read registry of client from server machine

by Ramki on Wednesday, March 16th 2005 at 06:16 AM

I want to get the web request made to my IIS server. I need the URL requested and the time of request.

by Andy Jump on Wednesday, March 16th 2005 at 06:52 AM

I think there are some registary classes in the .net framework so You'll want to look at those swapnil.

Ramki have a look through the wmi reference ... if its there then cool but i have a feeling you may have to do some work with asp.net

by Dilek on Friday, April 1st 2005 at 07:40 PM

hi &#305; wnat to system informati&#305;n get c# workgrup and servis pack can u help me

by Eranda on Saturday, April 16th 2005 at 10:09 AM

how to find hard disk information including capacity

by RamaDevi on Monday, October 17th 2005 at 07:53 AM

I am having an application where in, One thread will be tyring to read an Excel file using oledb.Second thread will be running simultaneouly, that will be creating an object of ManagementObjectSearcher and trying to get the Physical Memory Size.In this instance, once after reading the Excel file , the ManagementObjectSearcher is not able to create the instance.why??Pls if anyone know the answer , reply me.

Thanks!

by Kamakshi on Thursday, February 9th 2006 at 04:10 AM

I want to read database information of a remote machine using WMI. Which class will do this?

by srinivas on Thursday, March 2nd 2006 at 01:26 AM

Any body help me how to disable hard disk of a remote computer using wmi in vb/c#

by edwuave on Tuesday, May 9th 2006 at 03:20 AM

this one is c#, but anyone know how to do it in c++?

by Dorian on Saturday, September 2nd 2006 at 02:11 PM

You example is good but not enought reliable, I use Ionworx MachineID SDK v3.0 for .NET and Win32, it's very nice!

More details : http://www.ionworx.com/machineid.html

Regards,
Dorian

by dechkotzar on Friday, September 8th 2006 at 11:06 PM

Can some1 help me?

I'm trying to get partition information, and for every retreived partition I need to make another pictureBox control in my Form.

Thanks...

by ansar on Monday, September 11th 2006 at 12:05 AM

The above code is working fine in XP and 2k but not in 98 OS..
and also it is not retrieving some Harddisk serial number.

Can anyone give a better source or Win32 class that can be used to retrieve Harddisk serial number

by Andrei Pociu on Monday, September 11th 2006 at 12:10 AM

Indeed, it doesn't work on Windows 98 because the application requires .NET Framework. What you can reuse from this tutorial in an application created in C++ are the WMI queries.

by ansar on Monday, September 11th 2006 at 01:53 AM

Hey andrei Pociu,

Even with .Net FW also it will not work in Win98 OS.
Can u give some Win32 API or class that can be used to get HDD serial number.

by ansar on Thursday, September 14th 2006 at 02:15 AM

I got a code that can able to get Harddisk serial number in Winxp and Win 2k. But there is a probelm with this code too. This code is getting only the serial number of IDE HDD's.

Can someone help me in finding the serial number of All type of HDD's

by Rajeev Menon on Tuesday, July 10th 2007 at 10:13 AM

Your code to find Hard disk serial number is interesting, but when I tried the program, Serial number is showing different in Master and Slave mode.

In Master Mode
IDESAMSUNG SP0411N
S01JJ30Y275145

And in Slave mode
IDESAMSUNG SP0411N
30534a31334a5930373231353534202020202020

Any idea why this is happening? My computer is having only one HDD. The serial number in slave mode looks like the value returned by \"PNPDeviceID\" for \"SELECT * FROM Win32_DiskDrive\" query.

by cipher_nemo on Sunday, August 26th 2007 at 02:45 AM

Thank you for spending the time to write this and make the tutorial public. From your example I\'m now able to reference any WMI class through C#. Kudos for the KISS guide! :-)

by prabhakaran on Monday, August 27th 2007 at 02:02 AM

hi, i have one doubt. how can trim the text to 5 char..in C#.net
pls tell me..

by prabha

by Ashwini on Thursday, January 10th 2008 at 07:08 AM

hi, I have used this code.
But when I tried to retrieve the hard drive serial number, I am getting exception of \'Invalid class\' after
ManagementObjectSearcher MOS_HDSearcher = new ManagementObjectSearcher(\"SELECT * FROM Win32_PhysicalMedia\");

int i = 0;
foreach (ManagementObject MO_HD in MOS_HDSearcher.Get())

Please tell me how to get it working.


Thanks
-Ashwini

by Lpi on Friday, February 1st 2008 at 02:55 PM

Very simple. Just write this:

string serno = \"\";

ManagementObject o =
new ManagementObject(\"Win32_LogicalDisk.DeviceID=\\\"C:\\\"\");

serno = o.Properies[\"VolumeSerialNumber\"].Value.ToString();
...


and etc.

by karunesh on Tuesday, June 23rd 2009 at 07:35 AM

Sir,
I have tried above code using System.Management Class. But when i debug my code then my application hangs in between. when I was retrieving the hard disk information with thi line of code
foreach (ManagementObject MO_HD in MOS_HDSearcher.Get())

by Arul on Saturday, December 26th 2009 at 12:51 AM

Hi
I am trying to get my system hard disk serial No... If any one knows pls help me...

by Arul on Saturday, December 26th 2009 at 12:52 AM

Hi
I am trying to get my system hard disk serial No... If any one knows pls help me... in C#.net windows application



by Nanthini on Friday, February 12th 2010 at 03:28 AM

hi,
i am doing my project in p2p file sharing.In that i have to list the logical drives of a remote computer from my system using C#.Is this possible..or else is it possible with WMI scripting..Please help me..reply me as soon as possible..am in critical situation please..

by RIVERAShawn30 on Thursday, December 8th 2011 at 10:55 PM

Following my analysis, thousands of people all over the world receive the loan from different banks. Thence, there's great possibilities to find a financial loan in any country.

by one way backlinks on Saturday, December 10th 2011 at 08:33 AM

I got he thing for getting the The height of the content area of a browser(ie viewport), but how do i get the height of the entire browser in ie8 including menubar,toolbar etc.For browser's other than ie8 this one works but for ie8 this one do not works. and I introduce your website perfect for my needs. It contains wonderful and helpful posts. I mortal listing most of them and got a lot from them. To me, you are doing the eager set. Fuddle on this. ingest at locating In the end, I would same to give you for making given a very website. Or where I could also gain several of my ranches for marketing substance for you all budy who come up here

by Casper on Saturday, January 28th 2012 at 09:49 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by Rice Crispy Treats on Sunday, January 29th 2012 at 03:58 PM

I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.

by casino on Saturday, February 4th 2012 at 06:48 AM

I need to say that you are doing a fantastic job. Please keep up the great work.

by ForeclosureHelp.org on Saturday, February 4th 2012 at 08:53 PM

Informative and interesting which we share with you so i think so it is very useful and knowledgeable. I would like to thank you for the efforts. Grant Applications

by Bodybuilding Shop zum Muskelaufbau on Tuesday, February 14th 2012 at 08:10 AM

hese steps, you can save them to a file and send it to your support person, who can then open it up and view

by counter strike 1.6 download on Thursday, February 16th 2012 at 02:22 PM

You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand.

by Johnson City Homes Blog on Wednesday, February 29th 2012 at 01:21 PM

I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.

by Software fidelizacion clientes on Thursday, March 15th 2012 at 06:16 AM

Nuestro software de fidelización de clientes gestiona cualquier programa de fidelización de clientes. Economico.Consúltanos

by Offshore Company In UAE on Friday, March 16th 2012 at 06:29 AM

Please note this because we can catch early tickets if we have known the dates.

by musty on Tuesday, April 24th 2012 at 03:41 PM

hello ı need to know computer features as harddisc, ram, screan etc. in c#

by musty on Tuesday, April 24th 2012 at 03:41 PM

hello ı need to know computer features as harddisc, ram, screan etc. in c#

by musty on Tuesday, April 24th 2012 at 03:41 PM

hello ı need to know computer features as harddisc, ram, screan etc. in c#

by musty on Tuesday, April 24th 2012 at 03:41 PM

hello ı need to know computer features as harddisc, ram, screan etc. in c#

by musty on Tuesday, April 24th 2012 at 03:41 PM

hello ı need to know computer features as harddisc, ram, screan etc. in c#

by musty on Tuesday, April 24th 2012 at 03:41 PM

hello ı need to know computer features as harddisc, ram, screan etc. in c#

by Viagra on Monday, May 7th 2012 at 01:26 PM

If you wanna retrieve information about the CDROM drive on a machine, you can write some simple queries in c# and get that job done...thanks

by Virtualization on Sunday, May 13th 2012 at 04:54 AM

Thanks for this introduction.I'm very happy that there is someone out there who shares this information with us, the ones that are not that advanced in Java or C or #.

by VPN service reviews on Saturday, May 19th 2012 at 09:10 AM

Thanks so much for your comment. I am waiting for this information. Join now to share.

by VPN service reviews on Saturday, May 19th 2012 at 09:10 AM

Thanks so much for your comment. I am waiting for this information. Join now to share.

by Manoj on Saturday, July 14th 2012 at 12:55 AM

Getting Serial No as null . Why???

by Mar Smith on Monday, July 16th 2012 at 12:57 PM

Windows Management Instrumentation (WMI) is Microsoft’s implementation of Web-Based Enterprise Management (WBEM), an industry initiative to provide a Common Information Model (CIM) for pretty much any information about a computer system. The Python WMI module is a lightweight wrapper on top of the pywin32 extensions, and hides some of the messy plumbing needed to get Python to talk to the WMI API. Check http://www.activextest.com/run-activex.html for more info.

by http://www.activextest.com/run-activex.html on Monday, July 16th 2012 at 01:00 PM

Windows Management Instrumentation (WMI) is Microsoft's implementation of Web-Based Enterprise Management (WBEM), an industry initiative to provide a Common Information Model (CIM) for pretty much any information about a computer system. The Python WMI module is a lightweight wrapper on top of the pywin32 extensions, and hides some of the messy plumbing needed to get Python to talk to the WMI API.

by on Thursday, August 9th 2012 at 06:38 AM

you can create a management application that monitors an enterprise, provides event-based alerts, and allows a user to control different aspects of an enterprise.

by http://zhidain.soup.io/ on Friday, September 21st 2012 at 03:38 AM

If you wanna retrieve information about the CDROM drive on a machine, you can write some simple queries in c# and get that job done...thanks

by Locksmith Washington DC on Thursday, September 27th 2012 at 12:37 AM

An act of goodness is a smart financial commitment.

by Silver Spring Locksmith on Friday, September 28th 2012 at 01:22 AM

I appreciate the valuable details you provide in your material very awesome.

by aircraft insurance rates on Monday, October 1st 2012 at 02:07 AM

This post contains excellent original thinking. The informational content material here proves that points arent so black and white. I feel smarter from just reading this.

by top ipad business app on Tuesday, October 2nd 2012 at 03:41 AM

The informational content material here proves that points arent so black and white

by choosing an overhead projector on Wednesday, December 12th 2012 at 08:13 AM

It's an excellent demonstration of this problem. I am going to present your point of view to my students and I will ask them to think about other examples for this application, because there are many aspects that you didn't cover here.

by bicicletas holandesas on Wednesday, February 27th 2013 at 12:20 AM

Hi Buddy, Your blog website website is really style as fresh and fantastic and the details of your web page is very exciting, I really experienced it and I also want more details about this, thanks for discussing.
http://www.classicbikes.es/bicicletas/tienda-bicicletas-holandesas-de-segunda-mano


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources