Methods for controlling the services of a remote computer in C # _c# tutorial

Source: Internet
Author: User
provides classes in. NET to display and control services on Windows systems, and to enable access to remote computer service services, such as the ServiceController class under the System.ServiceProcess namespace, System.Management the classes of some of the WMI operations below. Although the use of ServiceController can be very convenient to achieve the control of the service, but also intuitive, concise and easy to understand. But I think his functionality is probably a little bit more than just using WMI to manipulate a service, and it can be cumbersome to operate on multiple services and not be able to list the specific data for all the services in the system. Here's how to use the System.Management component to manipulate services on remote and local computers.
WMI provides a scalable, extensible management architecture as part of the Windows 2000 operating system. The Public Information Model (CIM) is an extensible, object-oriented architecture designed by the Distributed Management Task Standards Association (DMTF) for managing systems, networks, applications, databases, and devices. The Windows management specification, also known as CIM for Windows, provides a uniform way to access management information. If you need to get detailed WMI information, ask your reader to review MSDN. The System.Management component provides access to a wide range of management information and management event collections related to system, device, and application setting checkpoints based on the Windows Management Instrumentation (WMI) architecture.
But the above is not our most concern, the following is the topic we need to talk about.
There is no doubt that we will refer to the SYSTEM.MANAGEMENT.DLL assembly and use the classes under the System.Management namespace, such as Managementclass,managementobject. The following is a class called Win32servicemanager that wraps some of the relevant operations of the service, the code reads 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 the 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;
}
Gets the value of the specified service property
public Object Getservicevalue (String servicename,string PropertyName)
{
ManagementObject mo = This.managementClass.CreateInstance ();
Mo. Path = new Managementpath (this.strpath+). Name=\ "" "+servicename+" "" ");
return Mo[propertyname];
}
Get all the service data for 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;
}
Gets the specified service data for the connected computer
public string [,] Getservicelist (string serverName)
{
Return Getservicelist (new string []{servername});
}
Gets the specified service data for 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 a 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 if you can pause
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 if you can recover
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 if you can stop
if ((bool) mo["AcceptStop"])//(String) mo["state"]== "Running"
Mo. InvokeMethod ("StopService", null);
}
catch (ManagementException e)
{
Strrst =e.message;
}
return strrst;
}
}
}
Remoteconnectvalidate static methods in Win32servicemanager to test the success of the connection, plus Getservicevalue method and Getservicelist method and its overload to obtain service information Four of the following methods are the state control of the service.
Let's create a simple window to use it.
The approximate interface is as follows:

The above form can be made quickly by Vs.net 2003, 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 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 ("The operation is successful, please click Get refresh button refresh result!");
Else
MessageBox.Show (Startrst);
Break
Case "Paused":
String startpause = This.serviceManager.PauseService (This.listviewservice.selecteditems[0]. Subitems[0]. Text);
if (startpause==null)
MessageBox.Show ("The operation is successful, please click Get refresh button refresh 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 ("The operation is successful, please click Get refresh button refresh 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 ("The operation is successful, please click Get refresh button refresh result!");
Else
MessageBox.Show (Startstop);
Break
}
}
Getting and refreshing data
private void Buttonloadrefresh_click (object sender, System.EventArgs e)
{
if (This.textBoxHost.Text.Trim (). LENGTH&GT;0)
{
if (this.textBoxHost.Text.Trim () = = ".")
{
This.servicemanager = new Win32servicemanager ();
}
Else
{
if (This.textBoxHost.Text.Trim (), This.textBoxName.Text.Trim (), Win32servicemanager.remoteconnectvalidate (), This.textBoxPassword.Text.Trim ()))
{
This.servicemanager = new Win32servicemanager (This.textBoxHost.Text.Trim (), This.textBoxName.Text.Trim (), This.textBoxPassword.Text.Trim ());
}
Else
{
MessageBox.Show ("Connect to remote computer validation error.");
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 ("Please enter a computer name or IP address");
}
}
}
Description, in fact, the properties and methods of a service in addition to these several there are many, we can instantiate the ManagementClass class, using its properties and methods attributes to list all the properties and methods. Each of the service instances generated in the Win32servicemanager above is managementobejct type, and there is a strongly typed class that can be generated by programming and tooling.
In summary, by referencing the System.Management namespace, it simply implements the display and operation of the service by accessing the \root\cimv2:win32_service namespace. In addition, we can access other namespaces to access some of the computer's hardware information, software information and network, interested readers can study.
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.