C # WMI answer highlights

Source: Internet
Author: User
Tags dot net

WMI tips
Many of my friends may have met WMI but do not have a deep understanding of it. I am also very interested in WMI knowledge. I have been searching for inappropriate information. Some information on the Internet is not wrong, I can't explain it clearly. When I have time, I will concentrate on WMI knowledge and put it here for your convenience. This post will be continuously added.

1. What is WMI?
WMI is an English Windows Management
Short for Instrumentation, its function is mainly: access some information and services of the local host, you can manage remote computers (of course you must have sufficient permissions), such as: restart, shutdown, shut down processes and create processes.

2. How can I use WMI to obtain information about a local disk?
First, you must create a project in VS. NET, and then reference A. net installation accessory: System. Management. dll in the Add reference, so that your project can use WMI. The Code is as follows:

Using System;
Using System. Management;

Class Sample_ManagementObject
{
Public static int Main (string [] args)
{
SelectQuery query = new SelectQuery ("Select * From Win32_LogicalDisk ");
ManagementObjectSearcher searcher = new ManagementObjectSearcher (query );
Foreach (ManagementBaseObject disk in searcher. Get ())
{
Console. WriteLine ("\ r \ n" + disk ["Name"] + "" + disk ["DriveType"] + "" +
Disk ["VolumeName"]);
}

Console. ReadLine ();

Return 0;

}

}

The return value of disk ["DriveType"] is as follows:

1 No type
2 Floppy disk
3 Hard disk
4 Removable drive or network drive
CD-ROM
6 RAM disk

3. How can I use WMI to obtain the capacity of a specified disk?
Using System;
Using System. Management;

// This example demonstrates reading a property of a ManagementObject.
Class Sample_ManagementObject
{
Public static int Main (string [] args)
{
ManagementObject disk = new ManagementObject (
"Win32_logicaldisk.deviceid = \" c :\"");
Disk. Get ();
Console. WriteLine ("Logical Disk Size =" + disk ["Size"] + "bytes ");
Console. ReadLine ();
Return 0;
}
}

4. How to list all the shared resources on the machine?
Using System;
Using System. Management;

Class TestApp {
[STAThread]
Static void Main ()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher (
"SELECT * FROM Win32_share ");
Foreach (ManagementObject share in searcher. Get ())
{
Console. WriteLine (share. GetText (TextFormat. Mof ));
}
}

}
Do not forget to add System. Management in the reference.

5. How can I write a process control to share a folder in the system or cancel sharing .?
First, you must log on to the system as a user with the relevant permissions. Then, try the following code:
Using System;
Using System. Management;

Class CreateShare
{
Public static void Main (string [] args)
{
ManagementClass _ class = new ManagementClass (new ManagementPath ("Win32_Share "));

Object [] obj = {"C: \ Temp", "my shares", "share implemented by Dot Net ",""};

_ Class. InvokeMethod ("create", obj );
}
}
Set
Object [] obj = {"C: \ Temp", "my shares", "share implemented by Dot Net ",""};
Change
Object [] obj = {"C: \ Temp", "my shares", 0, null, "share implemented by Dot Net ",""};
You can grant permissions to the most users.

6. How to obtain the running status of system services?
Private void getServices ()
{
ManagementObjectCollection queryCollection;
String [] lvData = new string [4];

Try
{
QueryCollection = getServiceCollection ("SELECT * FROM Win32_Service ");
Foreach (ManagementObject mo in queryCollection)
{
// Create child node for operating system
LvData [0] = mo ["Name"]. ToString ();
LvData [1] = mo ["StartMode"]. ToString ();
If (mo ["Started"]. Equals (true ))
LvData [2] = "Started ";
Else
LvData [2] = "Stop ";
LvData [3] = mo ["StartName"]. ToString ();

// Create list item
ListViewItem lvItem = new ListViewItem (lvData, 0 );
ListViewServices. Items. Add (lvItem );
}
}
Catch (Exception e)
{
MessageBox. Show ("Error:" + e );
}
}

7. How can I modify the IP address Through WMI without restarting?
Using System;
Using System. Management;
Using System. Threading;

Namespace WmiIpChanger
{
Class IpChanger
{
[MTAThread]
Static void Main (string [] args)
{
ReportIP ();
// SwitchToDHCP ();
SwitchToStatic ();
Thread. Sleep (5000 );
ReportIP ();
Console. WriteLine ("end .");
}

Static void SwitchToDHCP ()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass ("Win32_NetworkAdapterConfiguration ");

ManagementObjectCollection moc = mc. GetInstances ();
Foreach (ManagementObject mo in moc)
{
If (! (Bool) mo ["IPEnabled"])
Continue;

InPar = mo. GetMethodParameters ("EnableDHCP ");
OutPar = mo. InvokeMethod ("EnableDHCP", inPar, null );
Break;
}
}

Static void SwitchToStatic ()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass ("Win32_NetworkAdapterConfiguration ");

ManagementObjectCollection moc = mc. GetInstances ();
Foreach (ManagementObject mo in moc)
{
If (! (Bool) mo ["IPEnabled"])
Continue;

InPar = mo. GetMethodParameters ("EnableStatic ");
InPar ["IPAddress"] = new string [] {"192.168.1.1 "};
InPar ["SubnetMask"] = new string [] {"255.255.255.0 "};
OutPar = mo. InvokeMethod ("EnableStatic", inPar, null );
Break;
}
}

Static void ReportIP ()
{
Console. WriteLine ("****** Current IP addresses :");
ManagementClass mc = new ManagementClass ("Win32_NetworkAdapterConfiguration ");

ManagementObjectCollection moc = mc. GetInstances ();
Foreach (ManagementObject mo in moc)
{
If (! (Bool) mo ["IPEnabled"])
Continue;

Console. WriteLine ("{0} \ n SVC: '{1}' MAC: [{2}]", (string) mo ["Caption"],
(String) mo ["ServiceName"], (string) mo ["MACAddress"]);

String [] addresses = (string []) mo ["IPAddress"];
String [] subnets = (string []) mo ["IPSubnet"];

Console. WriteLine ("Addresses :");
Foreach (string sad in addresses)
Console. WriteLine ("\ t' {0} '", sad );

Console. WriteLine ("Subnets :");
Foreach (string sub in subnets)
Console. WriteLine ("\ t' {0} '", sub );
}
}
}
}

8. How can I remotely restart a remote computer Using WMI?
Using System;
Using System. Management;
Namespace WMI3
{
/// <Summary>
/// Summary description for Class1.
/// </Summary>
Class Class1
{
Static void Main (string [] args)
{
Console. WriteLine ("Computer details retrieved using Windows Management
Instrumentation (WMI )");
Console. WriteLine ("mailto: Written % 2002/01/02% 20By % 20 John % 20O 'Donnell % 20-% 20csharpconsulting@hotmail.com ");

Console. writeLine ("========================================== ===
===================================== ");
// Connect to a remote computer
ConnectionOptions co = new ConnectionOptions ();
Co. Username = "john ";
Co. Password = "john ";
System. Management. ManagementScope MS = new
System. Management. ManagementScope ("\\\\ 192.168.1.2 \\ root \ cimv2", co );
// Query remote computers
System. Management. ObjectQuery oq = new System. Management. ObjectQuery ("SELECT *
FROM Win32_OperatingSystem ");

ManagementObjectSearcher query1 = new ManagementObjectSearcher (MS, oq );
ManagementObjectCollection queryCollection1 = query1.Get ();
Foreach (ManagementObject mo in queryCollection1)
{
String [] ss = {""};
Mo. InvokeMethod ("Reboot", ss );
Console. WriteLine (mo. ToString ());
}
}
}
}

9. Use WMI to create a new process?
Using System;
Using System. Management;

// This sample demonstrates invoking a WMI method using parameter objects
Public class InvokeMethod
{
Public static void Main ()
{

// Get the object on which the method will be invoked
ManagementClass processClass = new ManagementClass ("Win32_Process ");

// Get an input parameters object for this method
ManagementBaseObject inParams = processClass. GetMethodParameters ("Create ");

// Fill in input parameter values
InParams ["CommandLine"] = "calc.exe ";

// Execute the method
ManagementBaseObject outParams = processClass. InvokeMethod ("Create", inParams,
Null );

// Display results
// Note: The return code of the method is provided in the "returnvalue" property
Of the outParams object
Console. WriteLine ("Creation of calculator process returned:" +
OutParams ["returnvalue"]);
Console. WriteLine ("Process ID:" + outParams ["processId"]);
}
}

10. How to terminate a Process Through WMI?
Using System;
Using System. Management;

// This example demonstrates how to stop a system service.
Class Sample_InvokeMethodOptions
{
Public static int Main (string [] args ){
ManagementObject service =
New ManagementObject ("win32_service = \" winmgmt \"");
InvokeMethodOptions options = new InvokeMethodOptions ();
Options. Timeout = new TimeSpan (0, 0, 0, 5 );

ManagementBaseObject outParams = service. InvokeMethod ("StopService", null,
Options );

Console. WriteLine ("Return Status =" + outParams ["Returnvalue"]);

Return 0;
}
}

11. How can I use WMI to obtain directories and files of remote machines? For example, how can I list all files in a directory or all subdirectories? How can I delete, lick, and modify files?
Using System;

Using System. Management;

// This example demonstrates reading a property of a ManagementObject.

Class Sample_ManagementObject

{

Public static int Main (string [] args ){

ManagementObject disk = new ManagementObject (

"Win32_logicaldisk.deviceid = \" c :\"");

Disk. Get ();

Console. WriteLine ("Logical Disk Size =" + disk ["Size"] + "bytes ");

Return 0;

}

}

12. References
You can refer to the following content:

Msdn wmi sdk:

Http://msdn.microsoft.com/library/default.asp? Url =/library/en-

Us/wmisdk/wmi/wmi_start_page.asp

WMI usage instructions (csdn ):
Http://www.csdn.net/develop/article/15/15346.shtm

Application of WMI Technology for. net (csdn ):
Http://www.csdn.net/develop/article/16/16419.shtm

Easily obtain system information in. NET (1)-WMI (csdn ):
Http://www.csdn.net/develop/article/15/15744.shtm

13. Tips
I can use WMI to retrieve the MAC address of the NIC, the serial number of the CPU, and the serial number of the motherboard. Among them, the serial number of the motherboard has been checked correctly, and the rest are to be verified, because I use a notebook and there is a Series Number of the motherboard on the back of the notebook, I can be sure that the series number of the motherboard is correct.

MAC address of the NIC

SELECT MACAddress FROM Win32_NetworkAdapter WHERE (MACAddress Is Not NULL) AND
(Manufacturer <> 'Microsoft '))

Result: 08: 00: 46: 63: FF: 8C

Serial number of the CPU

Select ProcessorId From Win32_Processor

Result: 3FEBF9FF00000F24

Motherboard serial number

Select SerialNumber From Win32_BIOS

Result: 28362630-3700521
Obtain the hard disk ID
String HDid;
ManagementClass cimobject = new ManagementClass ("Win32_DiskDrive ");
ManagementObjectCollection moc = cimobject. GetInstances ();
Foreach (ManagementObject mo in moc)
{
HDid = (string) mo. Properties ["Model"]. value;

MessageBox. Show (HDid );
}

14. An exception handling problem after WMI is used
Below is a piece of code I have compiled.

ManagementObjectCollection queryCollection1;
ConnectionOptions co = new ConnectionOptions ();
Co. Username = "administrator ";
Co. Password = "111 ";
Try
{
System. Management. ManagementScope MS = new
System. Management. ManagementScope (@ "\ csnt3 \ root \ cimv2", co );
System. Management. ObjectQuery oq = new System. Management. ObjectQuery ("SELECT *
FROM Win32_OperatingSystem ");
ManagementObjectSearcher query1 = new ManagementObjectSearcher (MS, oq );

QueryCollection1 = query1.Get ();
Foreach (ManagementObject mo in queryCollection1)
{
String [] ss = {""};
Mo. InvokeMethod ("Reboot", ss );
Console. WriteLine (mo. ToString ());
}
}
Catch (Exception ee)
{

Console. WriteLine ("error ");

}

15. Windows Management Specification (WMI) is a scalable system management structure. It adopts a unified, standard-based, and scalable object-oriented interface. WMI provides you with system management information and basics
Standard Method for wmi api interaction. WMI is mainly used by system management application developers and administrators to access and manage operating system information.
WMI can be used to generate organization and management system information tools so that administrators or system administrators can monitor system activities more closely. For example, you can use WMI to develop an application
Call the Administrator when the server crashes.
Use WMI with the. NET Framework
WMI provides a large number of specifications for many high-end applications (such as Microsoft Exchange, Microsoft SQL Server, and Microsoft
Internet Information Service (IIS) implements almost any management task. The administrator can perform the following tasks:
? Monitor the running status of the application.
? Detects bottlenecks or faults.
? Manage and configure applications.
? Query application data (using object link traversal and query ).
? Perform seamless local or remote management operations.
The WMI structure consists of the following three layers:
? Client
Software components that Use WMI to perform operations (such as reading management details, configuring systems, and booking events.
? Object Manager
Provides an intermediate device between the program and the client. It provides some key services, such as standard event publishing and booking, event filtering, and query engines.
? Providers
Software components that capture real-time data and return it to the client application, process method calls from the client, and link the client to the managed infrastructure.
The well-defined architecture provides clients and applications with the ability to seamlessly configure data and events and the system. In the. NET Framework, the System. Management namespace provides
Common classes of the WMI architecture.
In addition to the. NET Framework, WMI must be installed on the computer to use the management functions in the namespace. If you are using Windows Millennium
Edition, Windows 2000, or Windows XP, WMI has been installed. Otherwise, WMI needs to be downloaded from MSDN.
Access Management Information with System. Management
The System. Management namespace is the WMI namespace in the. NET Framework. This namespace includes the following first-level objects that support WMI operations:
? ManagementObject or ManagementClass: a single management object or class.
? ManagementObjectSearcher: used to retrieve ManagementObject or ManagementClass Based on the specified query or enumeration.
Object set.
? ManagementEventWatcher: Used to book event notifications from WMI.
? ManagementQuery: Used as the basis for all query classes.
The encoding example for the System. Management class is suitable for the. NET Framework environment, and WMI uses the standard base framework whenever appropriate. For example, WMI is widely used.
. NET collection class and use the recommended encoding mode, such as the "delegate" mode of. NET asynchronous operations. Therefore, use. NET
Framework developers can use their current skills to access management information about computers or applications.
See
Use WMI to manage applications | retrieve a collection of management objects | query Management Information | book and use management events | method of executing management objects | remote processing and connection options | use of strong objects

Code for obtaining the CPU serial number
String cpuInfo = ""; // cpu serial number
ManagementClass cimobject = new ManagementClass ("Win32_Processor ");
ManagementObjectCollection moc = cimobject. GetInstances ();
Foreach (ManagementObject mo in moc)
{
CpuInfo = mo. Properties ["ProcessorId"]. value. ToString ();
Console. WriteLine (cpuInfo );
Console. ReadLine ();
}
Obtain the network card hardware address
Using System. Management;
...
ManagementClass mc = new ManagementClass ("Win32_NetworkAdapterConfiguration ");

ManagementObjectCollection moc = mc. GetInstances ();
Foreach (ManagementObject mo in moc)
{
If (bool) mo ["IPEnabled"] = true)
Console. WriteLine ("MAC address \ t {0}", mo ["MacAddress"]. ToString ());
Mo. Dispose ();
}
}
Obtain the hard disk ID
String HDid;
ManagementClass cimobject = new ManagementClass ("Win32_DiskDrive ");
ManagementObjectCollection moc = cimobject. GetInstances ();
Foreach (ManagementObject mo in moc)
{
HDid = (string) mo. Properties ["Model"]. value;
MessageBox. Show (HDid );
}

16. easily retrieve system information in. NET (1)-WMI
Montaque
Statement:
1. My personal experience is for reference only
2. Retain the original Reprinted data.

Overview:
Do you have such experiences? Sometimes, to get a little bit of information about the system, such as considering the version number of the operating system or the resolution of the current screen. In fact, in the end, it is only a property value in a certain aspect of the read operating system. Then we can see the Win32
API declaration, call, code readability and maintainability are self-evident. In. NET, Microsoft provides more classes, and many methods to call APIs can be easily called in. NET. Today, we will briefly introduce how to use
Management specifications) to obtain information.
Main ideas:
Here is an example of how to obtain the shared directory of the operating System and the motherboard number, and how to use the class below System. Managment to obtain System-related information:

Body:
WMI (Windows Management Specification: Windows Management
Instrumentation is the implementation of Microsoft Web-Based Enterprise Management (WBEM) and a standard-based system management interface. WMI first appeared in Microsoft
Windows 2000, but it can also be installed on Windows NT 4 and Windows 9x computers. WMI is a powerful tool for getting system information easily.
In. NET, there is a System. management namespace (which is not referenced by the system by default. We can manually add references). Through the following Class operation, we can query system software and hardware information. Let's take a look at a simple example:

Imports System. Management
Dim searcher As New ManagementObjectSearcher ("SELECT * FROM Win32_share ")
Dim share As ManagementObject
For Each share In searcher. Get ()
MessageBox. Show (share. GetText (TextFormat. Mof ))
Next share
The running result lists the directories and descriptions currently shared by all systems.

Analyze the code above to see the following points:
1. It seems that the database is being operated, a bit like an SQL statement. It is actually an SQL operation. Such statements are converted into WQL (WMI Query
Language) is actually a subset of standard SQL with WMI extensions.
2. WQL is a read-only query language. We can only query the response data and cannot use UPDATE, INSERT, or other UPDATE operations.
3. The code is simple and easy to understand.
4. We use a MOF (managed object format) display.

Example 2: obtain information about the current Motherboard
The above example is a software information. Let's take a look at an example of obtaining hardware information to obtain the serial number of the motherboard and the manufacturer:
Dim searcher As New ManagementObjectSearcher ("SELECT * FROM Win32_BaseBoard ")

Dim share As ManagementObject
For Each share In searcher. Get ()
Debug. WriteLine ("motherboard Manufacturer:" & share ("Manufacturer "))
Debug. WriteLine ("model:" & share ("Product "))
Debug. WriteLine ("serial number:" & share ("SerialNumber "))
Next share
Summary and supplement:
WMI classes are also hierarchical. For details, refer to WMI in msdn. NET platform development, it is best to read more about.. NET introduces new features, which can greatly improve the Code development efficiency and running efficiency.

 

Related Article

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.