Use C # And WMI to obtain logical drive details

Source: Internet
Author: User
Use C # And WMI to obtain logical drive details By Dou ruixin Source: Tianji Development Responsible editor: Fangzhou
Write some windows management applications Program You can select from the custom drive selection list box is undoubtedly very professional, when using early versions of Delphi or C ++, we must use many API functions provided by Win32 to obtain disk information, such as the volume label, serial number, and remaining space, now we will use. net Framework and WMI (Windows Management Instrumentation-Windows Management specifications) to implement the above functions.

I. Introduction

If you only obtain the name list of the logical drive, we use.. NET Framework environment. getlogicaldrives. However, if you want more information about the disk drive, you can use it.. NET Framework. the classes and delegates provided by the management namespace access a large set of management information and management events. These information and events are related to WMI, the classes in this namespace are actually an encapsulation of WMI. applications and services can use classes derived from managementobjectsearcher and managementquery to query management information of interest, for example, the amount of available space on the disk, the current CPU usage, and the database to which an application is connected, now we will use the C # language to compile an example to obtain detailed logical drive information. NET framework system. management namespace related classes and WMI programming, such:

Ii. Technical Points

WMI was initially built into the core management support technology of Windows 2000, Windows XP, and Windows Server 2003 operating systems. Currently, WMI is a standard and basic structure, it allows you to access, configure, manage, and monitor almost all windows resources, such as disks, Event Logs, files, folders, file systems, network components, operating system settings, performance data, printers, processes, registry settings, security, services, sharing, users, groups, and so on. Before WMI, the only way to access windows resources programmatically is through the Win32 API. Now we can use WMI scripts to manage any windows resources exposed Through WMI.. NET Framework for WMI encapsulated system. management namespace.

We first Use WMI query to obtain the selectquery instance of a specific class name. There are two ways to create this instance. One is to pass a known class name, for example, the name of the class to be passed in this article is win32_logicaldisk,CodeAs follows:

Selectquery = new selectquery ("win32_logicaldisk ");

You can also use WQL query to create an instance of the query class. The Code is as follows:

Selectquery = new selectquery ("select * From win32_logicaldisk ");

You can also obtain only some attributes of a class. The Code is as follows:

Selectquery = new selectquery ("Select name, drivetype from win32_logicaldisk ");

The WQL Query Language is a subset of SQL. The query limits the returned data volume by containing the following content: 1. Select clause, specifying that only data of certain attributes is returned; 2. Where clause, specifying the instance to be returned. The win32_logicaldisk class cannot be found in the default local msdn. It can only be found in the online msdn, WMI under Win32 and COM development. There are many other classes that can also be used, the win32_account class that contains logon user information, the win32_printershare class that contains local and shared printer information, and so on. Win32_logicaldisk contains a wide range of drive attributes, such:

Then, use the specified selectquery query to create a managementobjectsearcher instance. This class is one of the more common entry points used to retrieve management information. The instance is created successfully, we need to call the get method to execute a query to retrieve the set of management objects. When this method is called, managementobjectsearcher executes the given Query within the specified range, return the set of management objects that match the query in the managementobjectcollection. This allows you to traverse all objects in the Set in a loop and obtain the attributes of the objects we are interested in. The Code is as follows:

......
Selectquery = new selectquery ("select * From win32_logicaldisk ");
Managementobjectsearcher searcher = new managementobjectsearcher (selectquery );

Int I = 0;
Foreach (managementobject disk in searcher. Get ()){
// Obtain the drive letter
Listview1.items. Add (Disk ["name"]. tostring ());
}
......

3. Program Implementation

We use Visual Studio 2005 to create this sample program. First, we create a blank project for the Windows Application in C # and name it getlogicdrives for the solution and project, on the default form1 form, we place a listview and a button control, keeping the default name of the control unchanged. Set the view attribute of listview1 to details, and double-click the columns attribute of listview1, add five columns for the Detail View: drive letter, volume label, type, capacity, and available space, set the text attribute of button1 to refresh, and add a click event for the button1, the Code is as follows:

Private void button#click (Object sender, eventargs E)
{
Listview1.items. Clear ();
Selectquery = new selectquery ("select * From win32_logicaldisk ");
Managementobjectsearcher searcher = new managementobjectsearcher (selectquery );
Int I = 0;
Foreach (managementobject disk in searcher. Get ()){
// Drive letter
Listview1.items. Add (Disk ["name"]. tostring ());
// Volume mark
Try
{
Listview1.items [I]. subitems. Add (Disk ["volumename"]. tostring ());
}
Catch
{
Listview1.items [I]. subitems. Add ("the device is not ready ");
}
// Drive type
String drivetype;
Try
{
Drivetype = disk ["drivetype"]. tostring ();
Switch (drivetype)
{
Case "0 ":
Listview1.items [I]. subitems. Add ("unknown device ");
Break;
Case "1 ":
Listview1.items [I]. subitems. Add ("not partitioned ");
Break;
Case "2 ":
Listview1.items [I]. subitems. Add ("removable disk ");
Break;
Case "3 ":
Listview1.items [I]. subitems. Add ("Hard Disk ");
Break;
Case "4 ":
Listview1.items [I]. subitems. Add ("network drive ");
Break;
Case "5 ":
Listview1.items [I]. subitems. Add ("Optical Drive ");
Break;
Case "6 ":
Listview1.items [I]. subitems. Add ("memory disk ");
Break;
}

}
Catch
{
Listview1.items [I]. subitems. Add ("unknown type ");
}
// Capacity
Try
{
Listview1.items [I]. subitems. Add (getsizeuseunit (Disk ["size"]. tostring ()));
}
Catch
{
Listview1.items [I]. subitems. Add ("the device is not ready ");
}
// Remaining space
Try
{
Listview1.items [I]. subitems. Add (getsizeuseunit (Disk ["freespace"]. tostring ()));
}
Catch
{
Listview1.items [I]. subitems. Add ("the device is not ready ");
}
I ++;
}
}

We use the getsizeuseunit function to format and display the disk space capacity. When this function is not used, the disk capacity and available space are displayed as follows:

Private string getsizeuseunit (string size)
{
Double DSpace = convert. todouble (size );
String sspace = DSpace. tostring ("N ");
String [] TMP;
String rtnsize = "0 ";

TMP = sspace. Split (',');
Switch (TMP. getupperbound (0 ))
{
Case 0:
Rtnsize = TMP [0] + "Byte ";
Break;
Case 1:
Rtnsize = TMP [0] + "." + TMP [1]. substring (0, 2) + "K ";
Break;
Case 2:
Rtnsize = TMP [0] + "." + TMP [1]. substring (0, 2) + "M ";
Break;
Case 3:
Rtnsize = TMP [0] + "." + TMP [1]. substring (0, 2) + "G ";
Break;
Case 4:
Rtnsize = TMP [0] + "." + TMP [1]. substring (0, 2) + "T ";
Break;
}
Return rtnsize;
}

After the preceding custom Formatting Function is used, the display of disk capacity and available space is very simple and intuitive.

Finally, to ensure that the drive information is automatically obtained when the form is started, you need to simulate the click operation on button1 in the form load event. The Code is as follows:

Private void form1_load (Object sender, eventargs E)
{
Button#click (sender, e );
}

Iv. Summary

We use. NET framework system. the WMI encapsulation provided by the management namespace is very simple to obtain detailed information about the logical drive. In addition to the above information, we can also easily obtain most information about Windows resources, WIN32API is simpler and more effective than WIN32API. This example program is compiled and debugged in Windows XP SP2 + Visual Studio 2005

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.