Introduction to class libraries manipulating WMI in Visual C #

Source: Internet
Author: User
Tags dot net locale switches

The

. NET Framework SDK provides comprehensive support for WMI, and the. NET Framework SDK provides a dedicated namespace "System.Management" for Visual C # to manipulate WMI. The namespace "System.Management" provides a large number of classes, interfaces, and enumerations that are used to handle WMI-related. The members of the

namespace "System.Management" are very complex, and it is not possible to fully introduce these members in space. According to my experience, to understand and master the use of WMI in Visual C #, the following six classes should be the focus of learning, namely ConnectionOptions, Managementscope, ObjectQuery, ManagementObjectSearcher, Managementobjectcollection and ManagementObject. Here's a quick introduction to six classes:

· The main function of the ConnectionOptions class

ConnectionOptions class is to provide all the required settings for the established WMI connection. When using WMI to operate on a remote computer, you first have to make a WMI connection, and the WMI connection is primarily in the Managementscope class, and a successful WMI connection will provide a remote computer WMI username and password. The ConnectionOptions class can provide this information through its properties. Table 01 is a few of the main properties of the ConnectionOptions class and its simple description.

Property Description
Authority Gets or sets the rights that will be used to authenticate the specified user.
Locale Gets or sets the locale that will be used for the connection operation.
Password Provides a password for WMI connection operations.
Username Provides the user name for the WMI connection operation.

Table 01:connectionoptions class Common properties and their descriptions

One of the most common properties is password and username.

· Managementscope class

The Managementscope class enables you to establish a WMI connection to a remote computer (or to a local computer) to represent an operational scope for management. There are two ways to create a WMI connection:

(1). Using the constructor, the Managementscope class instance is initialized with the following constructor, and the WMI connection is established, as follows:

Public Managementscope (
String path,
ConnectionOptions Options
) ;


Parameter: The server and namespace of the

path Managementscope. The

options contain connectionoptions about the options for the connection.

Using constructors is risky, because if you cannot establish a WMI connection based on the options provided, the program will get an exception and an error occurs.

The following code uses this constructor to build a Managementscope instance and establish a WMI connection to the remote computer majinhu: System.Management.ConnectionOptions Conn = new ConnectionOptions ();
//Set user name for WMI connection operation
Conn.username = "WMI User name";
//Set password for user
Conn.password = "This username corresponds to password";
System.Management.ManagementScope Ms = new Managementscope ("//majinhu/root/cimv2", Conn);


(2). Using the Connect method provided in Managementscope:

There are very few members in the Managementscope, the most commonly used methods and attributes: Common properties are options, which provide parameters primarily for WMI creation, and the common method is connect, which can be built on a remote computer's WMI connection. The following is a specific code to establish a WMI connection using the Connect method: System.Management.ConnectionOptions Conn = new ConnectionOptions ();
Set the user name for the WMI connection operation
Conn.username = "WMI User name";
Set the user's password
Conn.password = "This username corresponds to password";
System.Management.ManagementScope Ms = new Managementscope ("//majinhu/root/cimv2");
Ms.options = Conn;
Ms.connect ();
To establish a WMI connection


· ObjectQuery class

The ObjectQuery class or its derived class is used to specify the query in ManagementObjectSearcher. In the program, the query string is used to construct the ObjectQuery instance. The query string is a WQL language similar to the SQL language. The most common of the following ObjectQuery class constructors is the following syntax: Public ObjectQuery (
String query
) ;


Parameters:

string of query queries

· ManagementObjectSearcher class

ManagementObjectSearcher primarily retrieves a collection of WMI objects based on a specified query. ManagementObjectSearcher membership is also very simple, and its method get method is very important, managementobjectsearcher the WMI query through the Getting method and sets the resulting result. The return value of the Get method is an Managementobjectcollection instance that contains the object that matches the specified query.

Table 02 is a common attribute of its ManagementObjectSearcher class and its description.

Property Description
Options Options for how to search for objects
Query Queries invoked in the Finder
Scope The scope in which to find the object

Table 02:managementobjectsearcher class Common properties and their descriptions

· Managementobjectcollection class

The Managementobjectcollection class is very simple, and it mainly represents different collections of WMI instances, including namespaces, scopes, and query observers. There is no constructor for creating the Managementobjectcollection class.

· ManagementObject class

The ManagementObject class is a single managed object or class. You can use the methods in ManagementObject to invoke managementobject corresponding objects to perform the appropriate actions. The ManagementObject class is a rich class, and table 03 and table 04 are their common properties and methods.

Property Description
ClassPath The path of the object's class.
Options Additional information to use when retrieving an object.
Path The WMI path to the object.
Scope The scope in which this object resides.

Table 03:managementobject class Common properties and their descriptions

Method Description
Clone Creates a copy of the object.
CopyTo Copy the object to another location.
Delete Deletes an object.
Get Bind to an Administrative object.
getrelated Gets a collection of objects associated with this object (the contact object).
Getrelationships Gets the collection of associations for this object.
InvokeMethod Invokes the corresponding object method.
Put Commits changes made to the object.

Table 04:managementobject class common methods and their descriptions

The following is a combination of two specific examples that use this class in Visual C # to provide WMI mastering how to use WMI to write a network application, and the class library used primarily uses the six classes that are received above.

Two, one of the WMI network applications-get information for a remote computer
If you do not use WMI, the most common way to get system data for a remote computer is to run a client program on a remote computer that the local machine uses to obtain system data from the remote computer. This implementation is difficult both in programming and in the subsequent distribution of programs. And using WMI, everything seems very simple. The following is an example of the function of using WMI to get data for a remote computer's hard disk. You can get other data on the remote computer by simply modifying the program. The following are the specific implementation steps:
1. Start Visual Studio. Net First, select the file, new, Project menu, and then set the project type to Visual C # project in the New Project dialog box, set template to Windows application, type "Get remote computer hard drive Information" in the Name text box and type "E:/vs" in the text box in the location. NET project, and then click the OK button, so the project is set up.
2. Because of visual Studio. NET default compilation environment does not include the namespace System.Management container file System.Management.dll, so first introduce this DLL file into the project file. First select References in Solution Explorer, then click the right mouse button, in the pop-up menu, select Add Reference, in the Pop-up Add Reference dialog box, select the. Net page, and after selecting System.managemen in the Component Name column, click Select button You have added System.managemen in the Selected Components column, and then click OK, and now visual Studio. NET integrated development environment, namespace System.managemen is introduced.
3. In the Solution Explorer window, double-click the Form1.cs file to enter the editing interface of the Form1.cs file.  
4. At the beginning of the Form1.cs file, add after the system default import namespace:
using System.Management;
Used to refer to the namespace in which the WMI action class is located.
5. Take visual Studio. NET Current window to the Form1.cs window to design the form.
6. Adjust the values for each component property as follows:

Component type Component Name Property Setting the results
Form Form1 Text Get remote computer hard drive information
FormBorderStyle FixedSingle
MaximizeBox False
Textbox TextBox3 PasswordChar *
Button Button1 FlatStyle Flat

7. Take visual Studio. NET switches to the editing window of the Form1.cs file and replaces the processing code for the Button1 click event in Form1.cs with the following code. The following code acts as a WMI query to the remote computer, extracts the query to get the data, and displays the results:
private void Button1_Click (object sender, System.EventArgs e)
{
long MB = 1048576; 1024x1024
To set all the settings required for the generated WMI
System.Management.ConnectionOptions Conn = new ConnectionOptions ();
Conn.username = TextBox2.Text; User name
Conn.password = TextBox3.Text; Password
Set the scope used to perform WMI operations
System.Management.ManagementScope Ms = new Managementscope ("////" + TextBox1.Text + "//root//cimv2", Conn);
Try
{
Connect to the WMI scope of the actual operation
Ms.connect ();
Set the content to be queried through WMI
ObjectQuery Query = new ObjectQuery ("Select FreeSpace, Size, Name from Win32_LogicalDisk where drivetype=3");
WQL statements, set WMI query content, and WMI's scope of operations, retrieving a collection of WMI objects
ManagementObjectSearcher Searcher = new ManagementObjectSearcher (Ms, Query);
To invoke a WMI query asynchronously
Managementobjectcollection returncollection = Searcher.get ();
Double free = 0;
Double use = 0;
Double total = 0;
ListBox1.Items.Clear ();
Retrieve the hard drive information by retrieving the collection of instances of the generated WMI
foreach (ManagementObject return in returncollection)
{
LISTBOX1.ITEMS.ADD ("Disk name:" + return["name"]. ToString ());
Free = Convert.toint64 (return["FreeSpace"])/MB; Get free space on your hard disk
Use = (Convert.toint64 (return["Size")-Convert.toint64 (return["FreeSpace"))/mb;//Get the hard disk's used space
Get the total space on your hard disk
Total = Convert.toint64 (return["Size"])/MB;
LISTBOX1.ITEMS.ADD ("sum:" + total. ToString () + "MB");
LISTBOX1.ITEMS.ADD ("Used space:" + use.) ToString () + "MB");
LISTBOX1.ITEMS.ADD ("Available space:" + free.) ToString () + "MB");
}
}
catch (Exception ee)
{
MessageBox.Show ("Connection" + TextBox1.Text + "error, error message is:" + EE. Message, "There was an error. ");
}
}
8. Press the shortcut key F5 to run the program. After you have correctly entered the IP address or user name, Superuser name, and password of the remote computer, click the Get Hard disk information button, and the program will get the data for the hard disk of the specified computer and display it.
How to do, whether there is a sense of hacking. The following is an introduction to using WMI to complete a more "cool" program--restarting or shutting down a remote computer.
Third, WMI network applications--control of remote computers
Not only can WMI get the computer data it wants, but it can also be used for remote control. Remote control of computers is not only the dream of hackers, also most network managers are eager to get, especially in modern networks, every network administrator faces the LAN, are composed of a large computer group, if the effective management of each computer network is particularly important. At present, the common practice of network management software is to run the client program on the remote computer and run a control program on the local computer, which can realize the remote control of the computer through the direct communication of these two programs. The disadvantage of this approach is obvious, when the client shuts down the daemon, this remote management is not possible.
In fact, as a remote control software, WMI is a good choice, especially in Windows 2000, XP has become the mainstream operating system, the use of WMI to write remote control software can omit the previous remote control software one of the most headaches-the distribution of client programs.
The remote control program that is described in this section enables users to reboot and shut down remote computers. The following is a concrete implementation step of using WMI to control a remote computer in C #:
1. Start visual Studio. Net, select the file, new, Project menu, and then set the project type to Visual C # project in the New Project dialog box, set the template to Windows application, and in the name Type "Use WMI to control remote computer" in the text box and enter "E:/vs in the text box in the location." NET project, and then click the OK button, so the project is set up.
2. Repeat steps 2nd through 4th of the "Get remote computer hard drive Information" item.
3. Take visual Studio. NET Current window to the Form1.cs window, follow figure 3 for form design:
4. Adjust the values of each component's properties according to the data in the following table:
Component type Component Name Property Setting the results
Form Form1 Text Using WMI to control a remote computer
FormBorderStyle FixedSingle
MaximizeBox False
Textbox TextBox3 PasswordChar *
Button Button1 FlatStyle Flat
ComboBox ComboBox1 Items Reboot
Remote shutdown
5. Take visual Studio. NET switches to the editing window of the Form1.cs file and replaces the processing code for the Button1 click event in Form1.cs with the following code. The following code is useful for remote control of a remote computer based on the user's choice:
private void Button1_Click (object sender, System.EventArgs e)
{
Determining the scope of WMI operations
ConnectionOptions options = new ConnectionOptions ();

Options. Username = TextBox2.Text; User name
Options. Password = TextBox3.Text; User password
Try
{
Managementscope Conn = new Managementscope ("////" + TextBox1.Text + "//root//cimv2", options);
Conn.connect ();
Determining the contents of a WMI operation
ObjectQuery OQ = new ObjectQuery ("SELECT * from Win32_OperatingSystem");
ManagementObjectSearcher Query1 = new ManagementObjectSearcher (Conn, OQ);
Get WMI Action Content
Managementobjectcollection QueryCollection1 = Query1. Get ();
Perform the appropriate remote operation based on user selection
foreach (ManagementObject mo in QueryCollection1)
{
string [] ss= {"};

if (Combobox1.text = "reboot")
Mo. InvokeMethod ("Reboot", SS); Perform a reboot operation
else if (Combobox1.text = "Remote Shutdown")
Mo. InvokeMethod ("Shutdown", SS); Perform a remote shutdown
Else
MessageBox.Show ("Select an incorrect action.) "," the error. ");
}
}
catch (Exception ee)
{
MessageBox.Show ("Connection" + TextBox1.Text + "error, error message is:" + EE. message); Error
}
}
6. Press the F5 shortcut key, you can run the program. In the program's computer name or IP address text box, enter the name or IP address of the remote computer you want to control. In the user name with WMI permissions and password text box, enter the account and password with WMI operations, and after selecting the control type for the remote computer in the Select control type combo box, click Execution button, the program is able to control the specified remote computer accordingly.
Iv. Summary
With the above two examples, it can be seen that WMI is really a very useful thing, but because it is relatively new, domestic and even foreign countries do not have complete information, the above content is just to take you a brief look at WMI, in fact, through WMI to complete a lot of functions still need to explore, I hope that the content of this chapter , and mastering the way WMI is used is helpful.

Instance

WMI is a more confusing thing for most developers, and it's the same for me. It was only a little bit more familiar to WMI until I read a recent introduction to. Net Management. Here's a little bit of experience for friends who love C #.

WMI is a very powerful tool that can provide us with very powerful capabilities. For example, when we develop an application, we often need to get information about the local or remote operating system. Although it may seem normal, it's still a hassle to actually operate, especially if we want to get information about the remote operating system. WMI requires developers to access each other using a WQL approach. WQL allows us to use it just like we use Sql-link query language. As long as you know these classes and its field variables, you can easily get the information you want. Using WMI, a user can precisely define a data stream with a query. The query restricts the amount of data returned by specifying only those attributes of interest (in the SELECT statement) and retrieving only the entities of interest (using the WHERE clause). For example, if a user wants to retrieve all drives less than 2 MB on the computer (drives C, D, etc.):

SELECT * from Win32_LogicalDisk WHERE FreeSpace < 2000000

As you can see, it's fairly easy to use a simple WMI query. To achieve this, you need to refer to the System.Management namespace in. NET. As long as you know a little bit of database knowledge, we can use it to operate all our queries.

The System.Management namespace is the WMI namespace in the. NET framework. This namespace includes the following class objects:

ManagementObject or ManagementClass: a single Management object or class, respectively.

ManagementObjectSearcher: Used to retrieve a collection of ManagementObject or ManagementClass objects based on a specified query or enumeration.

ManagementEventWatcher: Used to subscribe event notifications from WMI.

Managementquery: Serves as the basis for all query classes.

The following code shows you how to use WMI to enumerate all the open processes on a remote machine.

private void Remoteenumerate_click (object sender, System.EventArgs e)

{

If you have access to a remote machine, you must connect, you can omit the local

connectionoptions oconn = new ConnectionOptions ();

Username and password are you must enter the other side, that is, the other assigned to you the right
Oconn.username = "Zhangdong"; Access to each other's user name
Oconn.password = "1234"; Access to each other's password

ServerName is the name of the other machine, can also be IP address,//root//cimv2 copy on the line
Managementpath p = new Managementpath ("
////servername//root//cimv2");

Managementscope ms = new Managementscope (p,oconn);

ObjectQuery OQ = new ObjectQuery ("SELECT * from Win32_Process");

ManagementObjectSearcher Query1 = new ManagementObjectSearcher (MS,OQ);

Managementobjectcollection QueryCollection1 = Query1. Get ();

Enumerate all the right image and display it in the ListBox

foreach (ManagementObject service in QueryCollection1)

{

The list box shows the name and path of the process, and of course, other information, such as process handle,//process priority, current running status, etc., we do not enumerate all of them, interested in you can own//have a try

ListBox1.Items.Add ("Service:" + service["Name"] + "FilePath:" + service["ExecutablePath"]);

}
}

As you can see, it's not hard to realize, it's pretty easy to say.

WMI method call
Another interesting aspect of WMI is the remote method invocation. Of course, the method is present in every WMI class, WMI

Class has its own method, and some WMI classes have no methods.     Now let's take a look at another WMI class. Win32_Share class, this WMI class has three methods: Create,delete,setshareinfo we only talk about one of the Create methods, and the remaining two methods are called the same way as other WMI classes.

The Create method is described as follows:

int Create

(String Sharepath;//shared path, you want to share that path

String sharename; After sharing, the name of the label when it is accessed

Int Sharetype; Share type, typically 0 to indicate disk sharing

Int maxusers; Maximum number of users

String Description; Describe

String PassWord; Access password

A return of 0 indicates that the share was created successfully. After the following program creates a share, you can see that the folder has been shared, or you can't see it, until you right-click and view the share. As in the form of C $, system-level sharing.

private void Remoteshare_click (object sender, System.EventArgs e)

{//Connect to the remote computer, we must first connect to it in order to operate it

ConnectionOptions myconnect = new ConnectionOptions ();

Myconnect.username = "Zhangdong";

Myconnect.password = "1234";

Managementpath remotenamespace = new Managementpath ("////servername//root//cimv2");

Managementscope myscope = new Managementscope (remotenamespace,myconnect);

To connect to the WMI class that you want to reference first here we refer to the Win32_Share class

Managementpath sharepath = new Managementpath ("Win32_Share");

Objectgetoptions otheroption = new Objectgetoptions (null,new

TimeSpan (0,0,10), true);

ManagementClass _processclass = new ManagementClass (Myscope, Sharepath,

Otheroption);

Object[] Sharea = {"C://program Files", "My Shares", 0,10, "Share of Dot Net implementations", ""};

Object result = _processclass.invokemethod ("Create", Sharea);

MessageBox (0, "The value returned is:" + result. ToString () + "share name:" + sharea[1], "share information", 0; }

The one thing we need to be aware of in terms of the above program is that we use the following form of parameter transfer

Object[] Sharea = {"C://program Files", "My Shares", 0,10, "Share of Dot Net implementations", ""};

This array represents the parameters passed in the method, and other method invocations in the WMI class can refer to this form.

As we said earlier, when enumerating all the open processes, if we want to shut down an open process remotely, we need to implement the following code:

foreach (ManagementObject service in QueryCollection1)

{//Judge whether the Delphi program is turned on, and if yes, close it

if (service["Name"). ToString () = = "Delphi32.exe")

{

String[] Tparas = {"0"}; Parameter array

Service. InvokeMethod ("Terminate", Tparas); Call to Terminate method

}

Enumerate the names of all processes and the path to this application, and of course some other attributes, except that this//is not listed

ListBox1.Items.Add ("Service:" + service["Name"] + "FilePath:" + service["ExecutablePath"]);

}

Summarize:

There are many other features about WMI, and I hope that this article gives you an idea of Windows management in. NET. Also want to love C # friends to communicate with each other a lot of experience

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.