Use C # To Control Remote Computer Services

Source: Internet
Author: User
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; Public win32servicemanager (): This (". ", null, null) {} public win32servicemanager (string host, string username, string password) {This. strpath = "//" + host + "// root // cimv2: win32_service"; this. managem Entclass = new managementclass (strpath); If (username! = NULL & username. length> 0) {connectionoptions = new connectionoptions (); connectionoptions. username = username; connectionoptions. password = password; managementscope = new managementscope ("//" + host + "// root // cimv2", connectionoptions); this. managementclass. scope = managementscope; }}// verify whether the machine can be connected to the remote computer public static bool remoteconnectvalidate (string host, string Username, string password) {connectionoptions = new connectionoptions (); connectionoptions. username = username; connectionoptions. password = password; managementscope = new managementscope ("//" + host + "// root // cimv2", connectionoptions); try {managementscope. connect ();} catch {} return managementscope. isconnected;} // get the value of the specified service attribute public object getserviceval UE (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. managementc Lass. 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 Public String [,] getservicelist (string [] Serv Ernames) {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 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 public string pauseservice (string servicename) {string strrst = NULL; managementobject mo = This. managementclass. createinstance (); Mo. path = new managementpath (this. strpath + ". name =/"" + servicename + "/" "); try {// determine whether the IF (bool) Mo [" acceptpause "] & (string) m can be paused O ["state"] = "running") Mo. invokemethod ("pauseservice", null);} catch (managementexception e) {strrst = E. message;} return strrst;} // restore the specified 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 IF (bool) Mo [" acceptpause "] & (string) Mo ["state"] = "paused") Mo. invokemethod ("resumeservice", null);} catch (managementexception e) {strrst = E. message;} return strrst;} // stop the specified public string stopservice (string servicename) {string strrst = NULL; managementobject mo = This. managementclass. createinstance (); Mo. path = new managementpath (this. strpath + ". name =/"" + servicename + "/" "); try {// determine whether to stop 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. In addition, the getservicevalue method, getservicelist method, and its overloading 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. The following lists some additional code:

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 button to refresh the 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 ("operation successful, please click get refresh button 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 button 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 button to refresh the result! "); Else MessageBox. show (startstop); break ;}// obtain and refresh the 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. tex T. 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 for verification. "); 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, in addition to the above, there are many attributes and methods of a service. We can instantiate the managementclass class, use its properties and Methods Properties to list all properties 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/root/cimv2: win32_service namespace to display and operate the service. 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.
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.