In. net provides some classes to display and control services on Windows systems, and can access remote computer services, such as System. serviceController class under the ServiceProcess namespace, System. management. Although ServiceController can easily control services, it is intuitive, concise, and easy to understand. However, I think its functions may be a bit simpler than WMI for service operations, and it may be troublesome to operate on multiple services, the data of all services in the system cannot be listed. Here we will talk about how to use the System. Management component to operate services on remote and local computers.
As part of the Windows 2000 operating system, WMI provides a scalable and scalable management architecture. the Common Information Model (CIM) is a scalable and object-oriented architecture designed by the Distributed Management Task Standards Association (DMTF, used to manage systems, networks, applications, databases, and devices. Windows Management specifications, also known as CIM for Windows, provide a unified way to access and manage information. For more information about WMI, see MSDN. System. the Management component provides access to a large number of Management information and Management event sets, which are related to Setting Detection Points for systems, devices, and applications according to the Windows Management Specification (WMI) structure.
But the above is not what we are most concerned about. The following are the topics we need to talk about.
Undoubtedly, we need to reference the System. Management. Dll assembly and use the classes in the System. Management namespace, such as ManagementClass and ManagementObject. The following uses a class named Win32ServiceManager to encapsulate some operations related to the service. The Code is as follows:
Using System;
Using System. Management;
Namespace ZZ. Wmi
{
Public class Win32ServiceManager
{
Private string strPath;
Private ManagementClass managementClass;
Public Win32ServiceManager (): this (".", null, null)
{
}
Public Win32ServiceManager (string host, string userName, string password)
{
This. strPath = "\\\\" + host + "\\ root \ cimv2: Win32_Service ";
This. managementClass = new ManagementClass (strPath );
If (userName! = Null & userName. Length> 0)
{
ConnectionOptions connectionOptions = new ConnectionOptions ();
ConnectionOptions. Username = userName;
ConnectionOptions. Password = password;
ManagementScope managementScope = new ManagementScope ("\\\\" + host + "\\ root \ cimv2", connectionOptions );
This. managementClass. Scope = managementScope;
}
}
// Verify that you can connect to a remote computer
Public static bool RemoteConnectValidate (string host, string userName, string password)
{
ConnectionOptions connectionOptions = new ConnectionOptions ();
ConnectionOptions. Username = userName;
ConnectionOptions. Password = password;
ManagementScope managementScope = new ManagementScope ("\\\\" + host + "\\ root \ cimv2", connectionOptions );
Try
{
ManagementScope. Connect ();
}
Catch
{
}
Return managementScope. IsConnected;
}
// Obtain the value of the specified service attribute
Public object GetServiceValue (string serviceName, string propertyName)
{
ManagementObject mo = this. managementClass. CreateInstance ();
Mo. Path = new ManagementPath (this. strPath + ". Name = \" "+ serviceName + "\"");
Return mo [propertyName];
}
// Obtain all service data of the connected computer
Public string [,] GetServiceList ()
{
String [,] services = new string [this. managementClass. GetInstances (). Count, 4];
Int I = 0;
Foreach (ManagementObject mo in this. managementClass. GetInstances ())
{
Services [I, 0] = (string) mo ["Name"];
Services [I, 1] = (string) mo ["DisplayName"];
Services [I, 2] = (string) mo ["State"];
Services [I, 3] = (string) mo ["StartMode"];
I ++;
}
Return services;
}
// Obtain the specified service data of the connected computer
Public string [,] GetServiceList (string serverName)
{
Return GetServiceList (new string [] {serverName });
}
// Obtain the specified service data of the connected computer
Public string [,] GetServiceList (string [] serverNames)
{
String [,] services = new string [serverNames. Length, 4];
ManagementObject mo = this. managementClass. CreateInstance ();
For (int I = 0; I <serverNames. Length; I ++)
{
Mo. Path = new ManagementPath (this. strPath + ". Name = \" "+ serverNames [I] + "\"");
Services [I, 0] = (string) mo ["Name"];
Services [I, 1] = (string) mo ["DisplayName"];
Services [I, 2] = (string) mo ["State"];
Services [I, 3] = (string) mo ["StartMode"];
}
Return services;
}
// Stop the specified service
Public string StartService (string serviceName)
{
String strRst = null;
ManagementObject mo = this. managementClass. CreateInstance ();
Mo. Path = new ManagementPath (this. strPath + ". Name = \" "+ serviceName + "\"");
Try
{
If (string) mo ["State"] = "Stopped ")//! (Bool) mo ["AcceptStop"]
Mo. InvokeMethod ("StartService", null );
}
Catch (ManagementException e)
{
StrRst = e. Message;
}
Return strRst;
}
// Pause the specified service
Public string PauseService (string serviceName)
{
String strRst = null;
ManagementObject mo = this. managementClass. CreateInstance ();
Mo. Path = new ManagementPath (this. strPath + ". Name = \" "+ serviceName + "\"");
Try
{
// Determine whether a pause is allowed
If (bool) mo ["acceptPause"] & (string) mo ["State"] = "Running ")
Mo. InvokeMethod ("PauseService", null );
}
Catch (ManagementException e)
{
StrRst = e. Message;
}
Return strRst;
}
// Restore the specified service
Public string ResumeService (string serviceName)
{
String strRst = null;
ManagementObject mo = this. managementClass. CreateInstance ();
Mo. Path = new ManagementPath (this. strPath + ". Name = \" "+ serviceName + "\"");
Try
{
// Determine whether the data can be recovered
If (bool) mo ["acceptPause"] & (string) mo ["State"] = "Paused ")
Mo. InvokeMethod ("ResumeService", null );
}
Catch (ManagementException e)
{
StrRst = e. Message;
}
Return strRst;
}
// Stop the specified service
Public string StopService (string serviceName)
{
String strRst = null;
ManagementObject mo = this. managementClass. CreateInstance ();
Mo. Path = new ManagementPath (this. strPath + ". Name = \" "+ serviceName + "\"");
Try
{
// Determine whether the instance can be stopped
If (bool) mo ["AcceptStop"]) // (string) mo ["State"] = "Running"
Mo. InvokeMethod ("StopService", null );
}
Catch (ManagementException e)
{
StrRst = e. Message;
}
Return strRst;
}
}
}
In Win32ServiceManager, The RemoteConnectValidate static method is used to test whether the connection is successful or not. In addition, the GetServiceValue method, GetServiceList method, and its overload method are provided to obtain service information; the following four methods are used to control the service status.
Create a simple window to use it.
The general interface is as follows:
Through vs.net 2003, you can quickly make the above form, and some additional code is listed below:
Using ZZ. Wmi;
Namespace ZZForm
{
Public class Form1: System. Windows. Forms. Form
{
//......
Private Win32ServiceManager serviceManager;
Public Form1 ()
{
InitializeComponent ();
This. serviceManager = null;
}
//......
[STAThread]
Static void Main ()
{
Application. Run (new Form1 ());
}
// Modify the service status
Private void buttonChangeState_Click (object sender, System. EventArgs e)
{
Switch (Button) sender). Text)
{
Case "start ":
String startRst = this. serviceManager. StartService (this. listViewService. SelectedItems [0]. SubItems [0]. Text );
If (startRst = null)
MessageBox. Show ("operation successful. Please click get refresh to refresh the result! ");
Else
MessageBox. Show (startRst );
Break;
Case "pause ":
String startPause = this. serviceManager. PauseService (this. listViewService. SelectedItems [0]. SubItems [0]. Text );
If (startPause = null)
MessageBox. Show ("operation successful. Please click get refresh to refresh the result! ");
Else
MessageBox. Show (startPause );
Break;
Case "continue ":
String startResume = this. serviceManager. ResumeService (this. listViewService. SelectedItems [0]. SubItems [0]. Text );
If (startResume = null)
MessageBox. Show ("operation successful. Please click get refresh to refresh the result! ");
Else
MessageBox. Show (startResume );
Break;
Case "stop ":
String startStop = this. serviceManager. StopService (this. listViewService. SelectedItems [0]. SubItems [0]. Text );
If (startStop = null)
MessageBox. Show ("operation successful. Please click get refresh to refresh the result! ");
Else
MessageBox. Show (startStop );
Break;
}
}
// Obtain and refresh data
Private void buttonLoadRefresh_Click (object sender, System. EventArgs e)
{
If (this. textBoxHost. Text. Trim (). Length> 0)
{
If (this. textBoxHost. Text. Trim () = ".")
{
This. serviceManager = new Win32ServiceManager ();
}
Else
{
If (Win32ServiceManager. RemoteConnectValidate (this. textBoxHost. Text. Trim (), this. textBoxName. Text. Trim (), this. textBoxPassword. Text. Trim ()))
{
This. serviceManager = new Win32ServiceManager (this. textBoxHost. Text. Trim (), this. textBoxName. Text. Trim (), this. textBoxPassword. Text. Trim ());
}
Else
{
MessageBox. Show ("An error occurred while connecting to the remote computer .");
Return;
}
}
String [,] services = serviceManager. GetServiceList ();
This. listViewService. BeginUpdate ();
This. listViewService. Items. Clear ();
For (int I = 0; I <services. GetLength (0); I ++)
{
ListViewItem item = new ListViewItem (new string [] {services [I, 0], services [I, 1], services [I, 2], services [I, 3]});
This. listViewService. Items. Add (item );
}
This. listViewService. EndUpdate ();
}
Else
MessageBox. Show ("Enter the computer name or IP address ");
}
}
}
Note: In fact, there are many other attributes and Methods of a service. We can instantiate the ManagementClass class and use its Properties and Methods attributes to list all attributes and Methods. Each service instance generated in Win32ServiceManager above is of the ManagementObejct type. In fact, there is also a strong type class that can be generated through programming and tools.
In summary, by referencing the System. Management namespace, the above simple implementation of the service by accessing the \ root \ cimv2: Win32_Service namespace to display and operate. In addition, we can also access some computer hardware information, software information, and networks by accessing other namespaces. If you are interested, you can study it.