C#启用服务 关闭服务 安装服务 卸载服务 .

一.C#运用ProcessStartInfo安装服务,卸载服务,启用服务,关闭服务的操作!

01.C#运用ProcessStartInfo安装服务,卸载服务,启用服务,关闭服务的操作!    
02.  /// <summary>   
03.    /// 从CMD运行里面启用服务   
04.    /// </summary>   
05.    /// <param name="sender"></param>   
06.    /// <param name="e"></param>   
07.    protected void Button4_Click1(object sender, EventArgs e)  
08.    {  
09.         //开启服务   
10.        ProcessStartInfo a = new ProcessStartInfo(@"c:/windows/system32/cmd.exe","/c  net start 服务名");  
11.        a.WindowStyle = ProcessWindowStyle.Hidden;  
12.        Process process = Process.Start(a);  
13.          
14.          
15.    }  
16.    protected void Button5_Click1(object sender, EventArgs e)  
17.    {  
18.         //关闭服务   
19.        ProcessStartInfo a = new ProcessStartInfo(@"c:/windows/system32/cmd.exe","/c  net stop 服务名");  
20.        a.WindowStyle = ProcessWindowStyle.Hidden;  
21.        Process process = Process.Start(a);  
22.          
23.          
24.    }  
25.    protected void Button6_Click1(object sender, EventArgs e)  
26.    {  
27.          ProcessStartInfo a = new ProcessStartInfo(@"D://zhengxinle//xiangmu//NetView//NetView//Transmit.exe" ,"-install");  
28.        Console.Write("安装服务成功");  
29.        a.WindowStyle = ProcessWindowStyle.Hidden;  
30.        Process process = Process.Start(a);  
31.}  
32.  
33.    protected void Button7_Click1(object sender, EventArgs e)  
34.    {  
35.          ProcessStartInfo a = new ProcessStartInfo(@"D://zhengxinle//xiangmu//NetView//NetView//Transmit.exe" ,"-remove");  
36.        Console.Write("卸载服务成功");  
37.        a.WindowStyle = ProcessWindowStyle.Hidden;  
38.        Process process = Process.Start(a);  
39.}  

二.通过API函数加载

01.using System.Configuration.Install;  
02.using System.ServiceProcess;  
03.using System.Runtime.InteropServices;  
04
05.#region DLLImport     
06.  
07.        [DllImport("advapi32.dll")]    
08.        public static extern IntPtr OpenSCManager(string lpMachineName,string lpSCDB, int scParameter);    
09.        [DllImport("Advapi32.dll")]     
10.        public static extern IntPtr CreateService(IntPtr SC_HANDLE,string lpSvcName,string lpDisplayName,       
11.          int dwDesiredAccess,int dwServiceType, int dwStartType,int dwErrorControl,string lpPathName,      
12.          string lpLoadOrderGroup,int lpdwTagId, string lpDependencies,string lpServiceStartName,string lpPassword);   
13.        [DllImport("advapi32.dll")]      
14.        public static extern void CloseServiceHandle(IntPtr SCHANDLE);    
15.        [DllImport("advapi32.dll")]     
16.        public static extern int StartService(IntPtr SVHANDLE,int dwNumServiceArgs,string lpServiceArgVectors);    
17.        [DllImport("advapi32.dll",SetLastError=true)]     
18.        public static extern IntPtr OpenService(IntPtr SCHANDLE,string lpSvcName,int dwNumServiceArgs);    
19.        [DllImport("advapi32.dll")]     
20.        public static extern int DeleteService(IntPtr SVHANDLE);     
21.        [DllImport("kernel32.dll")]     
22.        public static extern int GetLastError();    
23.  
24.        #endregion DLLImport   
25.  
26.  ///        
27.        /// 安装和运行      
28.        /// /// C#安装程序路径.      
29.        /// /// 服务名      
30.        /// /// 服务显示名称.      
31.        /// /// 服务安装是否成功.      
32.        public bool InstallService(string svcPath, string svcName, string svcDispName)     
33.        {      
34.            #region Constants declaration.        
35.            int SC_MANAGER_CREATE_SERVICE = 0x0002;      
36.            int SERVICE_WIN32_OWN_PROCESS = 0x00000010;       
37.            //int SERVICE_DEMAND_START = 0x00000003;        
38.            int SERVICE_ERROR_NORMAL = 0x00000001;      
39.            int STANDARD_RIGHTS_REQUIRED = 0xF0000;      
40.            int SERVICE_QUERY_CONFIG = 0x0001;       
41.            int SERVICE_CHANGE_CONFIG = 0x0002;      
42.            int SERVICE_QUERY_STATUS = 0x0004;       
43.            int SERVICE_ENUMERATE_DEPENDENTS = 0x0008;       
44.            int SERVICE_START =0x0010;       
45.            int SERVICE_STOP =0x0020;      
46.            int SERVICE_PAUSE_CONTINUE =0x0040;      
47.            int SERVICE_INTERROGATE =0x0080;      
48.            int SERVICE_USER_DEFINED_CONTROL =0x0100;       
49.            int SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |         
50.                SERVICE_QUERY_CONFIG |       
51.                SERVICE_CHANGE_CONFIG |       
52.                SERVICE_QUERY_STATUS |        
53.                SERVICE_ENUMERATE_DEPENDENTS |        
54.                SERVICE_START |        
55.                SERVICE_STOP |        
56.                SERVICE_PAUSE_CONTINUE |         
57.                SERVICE_INTERROGATE |        
58.                SERVICE_USER_DEFINED_CONTROL);       
59.            int SERVICE_AUTO_START = 0x00000002;      
60.            #endregion Constants declaration.        
61.            try    {       
62.                IntPtr sc_handle = OpenSCManager(null,null,SC_MANAGER_CREATE_SERVICE);      
63.                if (sc_handle.ToInt32() != 0)       
64.                {         
65.                    IntPtr sv_handle = CreateService(sc_handle,svcName,svcDispName,SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START,SERVICE_ERROR_NORMAL,svcPath,null,0,null,null,null);      
66.                    if(sv_handle.ToInt32() ==0)        
67.                    {        
68.                        CloseServiceHandle(sc_handle);        
69.                        return false;        
70.                    }       
71.                    else       
72.                    {        
73.                        //试尝启动服务        
74.                        int i = StartService(sv_handle,0,null);         
75.                        if(i==0)         
76.                        {          
77.                            return false;    
78.                        }         
79.                        CloseServiceHandle(sc_handle);        
80.                        return true;       
81.                    }       
82.                }       
83.                else        
84.                    return false;   
85.            }       
86.            catch(Exception e)   
87.     
88.            {       
89.                throw e;      
90.            }    
91.        }  
92///        
93.        /// 反安装服务.     
94.        /// ///        
95.        /// 服务名.       
96.        public bool UnInstallService(string svcName)     
97.        {      
98.            int GENERIC_WRITE = 0x40000000;      
99.            IntPtr sc_hndl = OpenSCManager(null,null,GENERIC_WRITE);       
100.            if(sc_hndl.ToInt32() !=0)      
101.            {      int DELETE = 0x10000;     
102.                IntPtr svc_hndl = OpenService(sc_hndl,svcName,DELETE);      
103.                if(svc_hndl.ToInt32() !=0)       
104.                {         
105.                    int i = DeleteService(svc_hndl);     
106.                    if (i != 0)         
107.                    {          
108.                        CloseServiceHandle(sc_hndl);        
109.                        return true;        
110.                    }        
111.                    else       
112.                    {          
113.                        CloseServiceHandle(sc_hndl);        
114.                        return false;       
115.                    }       
116.                }       
117.                else     
118.                    return false;       
119.            }       
120.            else     
121.                return false;    
122.        }    

三.加载一个程序集,并运行其中的所有安装程序。

01.////////@@@是服务的名字   
02.    /// <summary>   
03.    /// 用ServiceController启用服务   
04.    /// </summary>   
05.    /// <param name="sender"></param>   
06.    /// <param name="e"></param>   
07.    protected void Button5_Click(object sender, EventArgs e)  
08.    {  
09.        System.ServiceProcess.ServiceController   myController   =  
10.              new System.ServiceProcess.ServiceController("@@@");     
11.     
12///ContinuePending 服务即将继续。这对应于 Win32 SERVICE_CONTINUE_PENDING 常数,该常数定义为 0x00000005。     
13//Paused 服务已暂停。这对应于 Win32 SERVICE_PAUSED 常数,该常数定义为 0x00000007。     
14//PausePending 服务即将暂停。这对应于 Win32 SERVICE_PAUSE_PENDING 常数,该常数定义为 0x00000006。     
15//Running 服务正在运行。这对应于 Win32 SERVICE_RUNNING 常数,该常数定义为 0x00000004。     
16//StartPending 服务正在启动。这对应于 Win32 SERVICE_START_PENDING 常数,该常数定义为 0x00000002。     
17//Stopped 服务未运行。这对应于 Win32 SERVICE_STOPPED 常数,该常数定义为 0x00000001。     
18//StopPending 服务正在停止。这对应于 Win32 SERVICE_STOP_PENDING 常数,该常数定义为 0x00000003。     
19.  
20.        if (myController.Status.Equals(ServiceControllerStatus.Stopped)||myController.Status.Equals(ServiceControllerStatus.StopPending))  
21.        {     
22.              myController.Start();  
23.            this.Button5.Text="关闭服务";  
24.              Response.Write("<mce:script language=javascript><!--  
25.alert('开启');  
26.// --></mce:script>");   
27.        }    
28.        else  
29.        {  
30.              myController.Stop();  
31.            this.Button5.Text="开启服务";  
32.            Response.Write("<mce:script language=javascript><!--  
33.alert('关闭服务');  
34.// --></mce:script>");   
35.        }  
36.  
37.    }  
38.  
39.  
40.一、安装服务:  
41.  
42.private void InstallService(IDictionary stateSaver, string filepath)  
43.  
44.        {  
45.  
46.            try  
47.  
48.            {  
49.  
50.                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("ServiceName");  
51.  
52.                if(!ServiceIsExisted("ServiceName"))  
53.  
54.                {  
55.  
56.                    //Install Service   
57.  
58.                    AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();  
59.  
60.                    myAssemblyInstaller.UseNewContext = true;  
61.  
62.                    myAssemblyInstaller.Path =filepath;  
63.  
64.                    myAssemblyInstaller.Install(stateSaver);  
65.  
66.                    myAssemblyInstaller.Commit(stateSaver);  
67.  
68.                    myAssemblyInstaller.Dispose();  
69.  
70.                    //--Start Service   
71.  
72.                    service.Start();  
73.  
74.                }  
75.  
76.                else  
77.  
78.                {  
79.  
80.                    if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)  
81.  
82.                    {  
83.  
84.                        service.Start();  
85.  
86.                    }  
87.  
88.                }  
89.  
90.            }  
91.  
92.            catch (Exception ex)  
93.  
94.            {  
95.  
96.                throw new Exception("installServiceError/n" + ex.Message);  
97.  
98.            }  
99.  
100.        }  
101.  
102.二、卸载windows服务:  
103.  
104.        private void UnInstallService(string filepath)  
105.  
106.        {  
107.  
108.            try  
109.  
110.            {  
111.  
112.                if (ServiceIsExisted("ServiceName"))  
113.  
114.                {  
115.  
116.                    //UnInstall Service   
117.  
118.                    AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();  
119.  
120.                    myAssemblyInstaller.UseNewContext = true;  
121.  
122.                    myAssemblyInstaller.Path = filepath;  
123.  
124.                    myAssemblyInstaller.Uninstall(null);  
125.  
126.                    myAssemblyInstaller.Dispose();  
127.  
128.                }  
129.  
130.            }  
131.  
132.            catch (Exception ex)  
133.  
134.            {  
135.  
136.                throw new Exception("unInstallServiceError/n" + ex.Message);  
137.  
138.            }  
139.  
140.        }  
141.  
142.三、判断window服务是否存在:  
143.  
144.        private bool ServiceIsExisted(string serviceName)  
145.  
146.        {  
147.  
148.            ServiceController[] services = ServiceController.GetServices();  
149.  
150.            foreach (ServiceController s in services)  
151.  
152.            {  
153.  
154.                if (s.ServiceName == serviceName)  
155.  
156.                {  
157.  
158.                    return true;  
159.  
160.                }  
161.  
162.            }  
163.  
164.            return false;  
165.  
166.        }  
167.  
168.四、启动服务:  
169.  
170.private void StartService(string serviceName)  
171.  
172.        {  
173.  
174.            if (ServiceIsExisted(serviceName))  
175.  
176.            {  
177.  
178.                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);  
179.  
180.                if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)  
181.  
182.                {  
183.  
184.                    service.Start();  
185.  
186.                    for (int i = 0; i < 60; i++)  
187.  
188.                    {  
189.  
190.                        service.Refresh();  
191.  
192.                        System.Threading.Thread.Sleep(1000);  
193.  
194.                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)  
195.  
196.                        {  
197.  
198.                            break;  
199.  
200.                        }  
201.  
202.                        if (i == 59)  
203.  
204.                        {  
205.  
206.                            throw new Exception(startServiceError.Replace("$s$", serviceName));  
207.  
208.                        }  
209.  
210.                    }  
211.  
212.                }  
213.  
214.            }  
215.  
216.        }  
217.  
218.五、停止服务:  
219.  
220.        private void StopService(string serviceName)  
221.  
222.        {  
223.  
224.            if (ServiceIsExisted(serviceName))  
225.  
226.            {  
227.  
228.                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);  
229.  
230.                if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)  
231.  
232.                {  
233.  
234.                    service.Stop();  
235.  
236.                    for (int i = 0; i < 60; i++)  
237.  
238.                    {  
239.  
240.                        service.Refresh();  
241.  
242.                        System.Threading.Thread.Sleep(1000);  
243.  
244.                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)  
245.  
246.                        {  
247.  
248.                            break;  
249.  
250.                        }  
251.  
252.                        if (i == 59)  
253.  
254.                        {  
255.  
256.                            throw new Exception(stopServiceError.Replace("$s$", serviceName));  
257.  
258.                        }  
259.  
260.                    }  
261.  
262.                }  
263.  
264.            }  
265.  
266.        }  
267.  
268.  
269.注:手动安装window服务的方法:  
270.  
271.在“Visual Studio 2005 命令提示”窗口中,运行:  
272.  
273.安装服务:installutil servicepath  
274.  
275.卸除服务:installutil /u servicepath  
原文地址:https://www.cnblogs.com/tearer/p/2284433.html