C # Install and uninstall a tool for Windows Services-source code

Source: Internet
Author: User

C # Install and uninstall a tool for Windows Services-source code
In our work, we often encounter installation and uninstallation of Windows Services. In the past, the company also wrote a WinForm program to select the installation path. This time, we came up with a small and flexible console program, you do not need to choose any more. You can install or uninstall the service by running it in the directory where you want to install the service. Development Concept 1. Due to system permission restrictions, you must run the program as an administrator. 2. You need to install and uninstall the program, when the program is running, the system prompts whether to install or uninstall the program. Enter 1 or 2. The program will find the executable files in the current directory and filter the program itself and the files with vhost file, and list the list for the operator to select (usually only one) 4. install or uninstall based on the user's choice 5. due to repeated operations, you need to call the specific implementation recursively first to operate the service, you need to use System. serviceProcess to encapsulate implementation classes

1 using System; 2 using System. collections; 3 using System. configuration. install; 4 using System. linq; 5 using System. serviceProcess; 6 7 namespace AutoInstallUtil 8 {9 public class SystemServices 10 {11 // <summary> 12 // Open System Service 13 /// </summary> 14 // <param name = "serviceName"> System Service name </param> 15 // <returns> </returns> 16 public static bool SystemServiceOpen (string serviceName) 17 {18 try 19 {20 using (var control = new ServiceController (serviceName) 21 {22 if (control. Status! = ServiceControllerStatus. running) 23 {24 control. start (); 25} 26} 27 return true; 28} 29 catch 30 {31 return false; 32} 33} 34 35 36 // <summary> 37 // close system service 38 // </summary> 39 // <param name = "serviceName"> system Service name </param> 40 // <returns> </returns> 41 public static bool SystemServiceClose (string serviceName) 42 {43 try 44 {45 using (var control = new ServiceController (serviceName) 46 {47 48 if (control. status = ServiceControllerStatus. running) 49 {50 control. stop (); 51} 52} 53 return true; 54} 55 catch 56 {57 return false; 58} 59} 60 61 // <summary> 62 // restart the system service 63 // </summary> 64 // <param name = "serviceName"> System service name </param> 65 // <returns> </returns> 66 public static bool SystemServiceReStart (string serviceName) 67 {68 try 69 {70 using (var control = new ServiceController (serviceName) 71 {72 if (control. status = System. serviceProcess. serviceControllerStatus. running) 73 {74 control. continue (); 75} 76} 77 return true; 78} 79 catch 80 {81 return false; 82} 83} 84 85 // <summary> 86 // return service status 87 // </summary> 88 // <param name = "serviceName"> System service name </param> 89 // <returns> 1: service not running 2: the service is starting 3: the service is stopped 4: the service is running 5: the service is about to continue 6: the service is about to be suspended 7: the service has been suspended 0: unknown Status </returns> 90 public static int GetSystemServiceStatus (string serviceName) 91 {92 try 93 {94 using (var control = new ServiceController (serviceName) 95 {96 return (int) control. status; 97} 98} 99 catch100 {101 return 0; 102} 103} 104 105 // <summary> 106 // return service status 107 // </summary> 108 // <param name = "serviceName"> System service name </param> 109 // <returns> 1: service not running 2: the service is starting 3: the service is stopped 4: the service is running 5: the service is about to continue 6: the service is about to be suspended 7: the service has been suspended 0: unknown status </returns> 110 public static string GetSystemServiceStatusString (string serviceName) 111 {112 try113 {114 using (var control = new ServiceController (serviceName) 115 {116 var status = string. empty; 117 switch (int) control. status) 118 {119 case status = "the service is not running"; 121 break; 122 case status = "the service is starting"; 124 break; 125 case status = "the service is stopping"; 127 break; 128 case status = "the service is running"; 130 break; 131 case status = "the service is about to continue "; 133 break; 134 case status = "the service is about to be suspended"; 136 break; 137 case status = "the service is suspended"; 139 break; 140 case 0: 141 status = "unknown state"; 142 break; 143} 144 return status; 145} 146} 147 catch148 {149 return "unknown state "; 150} 151} 152 153 // <summary> 154 // install service 155 // </summary> 156 // <param name = "stateSaver"> </ param> 157 // <param name = "filepath"> </param> 158 public static void InstallService (IDictionary stateSaver, string filepath) 159 {160 try161 {162 var myAssemblyInstaller = new AssemblyInstaller163 {164 UseNewContext = true, 165 Path = filepath166}; 167 myAssemblyInstaller. install (stateSaver); 168 myAssemblyInstaller. commit (stateSaver); 169 myAssemblyInstaller. dispose (); 170} 171 catch (Exception ex) 172 {173 throw new Exception ("installServiceError/n" + ex. message); 174} 175} 176 177 public static bool ServiceIsExisted (string serviceName) 178 {179 ServiceController [] services = ServiceController. getServices (); 180 return services. any (s => s. serviceName = serviceName ); 181} 182 183 // <summary> 184 // uninstall service 185 // </summary> 186 // <param name = "filepath"> path and file name </param> 187 public static void UnInstallService (string filepath) 188 {189 try190 {191 // UnInstall Service 192 var myAssemblyInstaller = new AssemblyInstaller193 {194 UseNewContext = true, 195 Path = filepath196}; 197 myAssemblyInstaller. uninstall (null); 198 myAssemblyInstaller. dispose (); 199} 200 catch (Exception ex) 201 {202 throw new Exception ("unInstallServiceError/n" + ex. message); 203} 204} 205} 206}

 

Next, we encapsulate the console operation method. recursion is used here to implement loop listening.
1 using System; 2 using System. diagnostics; 3 using System. IO; 4 using System. linq; 5 6 namespace AutoInstallUtil 7 {8 class Program 9 {10 static void Main (string [] args) 11 {12 try13 {14 ServerAction (); 15} 16 catch (Exception ex) 17 {18 Console. writeLine ("error: {0}", ex. message); 19} 20 21 Console. readKey (); 22} 23 24 // <summary> 25 // operation 26 /// </summary> 27 private static void ServerAction () 28 {29 C Onsole. writeLine ("Enter: 1 Install 2 Uninstall"); 30 var condition = Console. readLine (); 31 var currentPath = Environment. currentDirectory; 32 var currentFileNameVshost = Path. getFileName (Process. getCurrentProcess (). mainModule. fileName ). toLower (); 33 var currentFileName = currentFileNameVshost. replace (".vshost.exe ",". exe "); 34 var files = 35 Directory. getFiles (currentPath) 36. select (o => Path. getFileName (o ). toLower () 3 7. ToList () 38. Where (39 o => 40 o! = CurrentFileNameVshost41 & o! = CurrentFileName42 & o. ToLower (). EndsWith (". exe") 43 & o! = "Installutil.exe" 44 &&! O. toLower (). endsWith (".vshost.exe") 45. toList (); 46 if (files. count = 0) 47 {48 Console. writeLine ("the executable file is not found. Make sure there is a service program to be installed in the current directory"); 49} 50 else51 {52 Console. writeLine ("find the directory with the following executable files, please select the file number to install or uninstall:"); 53} 54 int I = 0; 55 foreach (var file in files) 56 {57 Console. writeLine ("No.: {0} file name: {1}", I, file); 58 I ++; 59} 60 var serviceFileIndex = Console. readLine (); 61 var servicePathName = currentPath + "\" + files [Convert. toInt32 (serviceFileIndex)]; 62 if (condition = "1") 63 {64 SystemServices. installService (null, servicePathName); 65} 66 else67 {68 SystemServices. unInstallService (servicePathName); 69} 70 Console. writeLine ("************ completed this operation **********"); 71 ServerAction (); 72} 73}

 

 

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.