C#啓用服務 關閉服務 安裝服務 卸載服務 收藏

一.C#運用ProcessStartInfo安裝服務,卸載服務,啓用服務,關閉服務的操作!

view plaincopy to clipboardprint?
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.} 
C#運用ProcessStartInfo安裝服務,卸載服務,啓用服務,關閉服務的操作! 
  /// <summary>
    /// 從CMD運行裏面啓用服務
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button4_Click1(object sender, EventArgs e)
    {
         //開啓服務
        ProcessStartInfo a = new ProcessStartInfo(@"c:/windows/system32/cmd.exe","/c  net start 服務名");
        a.WindowStyle = ProcessWindowStyle.Hidden;
        Process process = Process.Start(a);
       
       
    }
    protected void Button5_Click1(object sender, EventArgs e)
    {
         //關閉服務
        ProcessStartInfo a = new ProcessStartInfo(@"c:/windows/system32/cmd.exe","/c  net stop 服務名");
        a.WindowStyle = ProcessWindowStyle.Hidden;
        Process process = Process.Start(a);
       
       
    }
    protected void Button6_Click1(object sender, EventArgs e)
    {
          ProcessStartInfo a = new ProcessStartInfo(@"D://zhengxinle//xiangmu//NetView//NetView//Transmit.exe" ,"-install");
        Console.Write("安裝服務成功");
        a.WindowStyle = ProcessWindowStyle.Hidden;
        Process process = Process.Start(a);
}

    protected void Button7_Click1(object sender, EventArgs e)
    {
          ProcessStartInfo a = new ProcessStartInfo(@"D://zhengxinle//xiangmu//NetView//NetView//Transmit.exe" ,"-remove");
        Console.Write("卸載服務成功");
        a.WindowStyle = ProcessWindowStyle.Hidden;
        Process process = Process.Start(a);
}


二.通過API函數加載

view plaincopy to clipboardprint?
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.        }   
using System.Configuration.Install;
using System.ServiceProcess;
using System.Runtime.InteropServices;

#region DLLImport 

        [DllImport("advapi32.dll")] 
        public static extern IntPtr OpenSCManager(string lpMachineName,string lpSCDB, int scParameter); 
        [DllImport("Advapi32.dll")]  
        public static extern IntPtr CreateService(IntPtr SC_HANDLE,string lpSvcName,string lpDisplayName,    
          int dwDesiredAccess,int dwServiceType, int dwStartType,int dwErrorControl,string lpPathName,   
          string lpLoadOrderGroup,int lpdwTagId, string lpDependencies,string lpServiceStartName,string lpPassword);
        [DllImport("advapi32.dll")]   
        public static extern void CloseServiceHandle(IntPtr SCHANDLE); 
        [DllImport("advapi32.dll")]  
        public static extern int StartService(IntPtr SVHANDLE,int dwNumServiceArgs,string lpServiceArgVectors); 
        [DllImport("advapi32.dll",SetLastError=true)]  
        public static extern IntPtr OpenService(IntPtr SCHANDLE,string lpSvcName,int dwNumServiceArgs); 
        [DllImport("advapi32.dll")]  
        public static extern int DeleteService(IntPtr SVHANDLE);  
        [DllImport("kernel32.dll")]  
        public static extern int GetLastError(); 
 
        #endregion DLLImport

  ///    
        /// 安裝和運行  
        /// /// C#安裝程序路徑.  
        /// /// 服務名  
        /// /// 服務顯示名稱.  
        /// /// 服務安裝是否成功.  
        public bool InstallService(string svcPath, string svcName, string svcDispName)  
        {   
            #region Constants declaration.    
            int SC_MANAGER_CREATE_SERVICE = 0x0002;   
            int SERVICE_WIN32_OWN_PROCESS = 0x00000010;    
            //int SERVICE_DEMAND_START = 0x00000003;    
            int SERVICE_ERROR_NORMAL = 0x00000001;   
            int STANDARD_RIGHTS_REQUIRED = 0xF0000;   
            int SERVICE_QUERY_CONFIG = 0x0001;    
            int SERVICE_CHANGE_CONFIG = 0x0002;   
            int SERVICE_QUERY_STATUS = 0x0004;    
            int SERVICE_ENUMERATE_DEPENDENTS = 0x0008;    
            int SERVICE_START =0x0010;    
            int SERVICE_STOP =0x0020;   
            int SERVICE_PAUSE_CONTINUE =0x0040;   
            int SERVICE_INTERROGATE =0x0080;   
            int SERVICE_USER_DEFINED_CONTROL =0x0100;    
            int SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |      
                SERVICE_QUERY_CONFIG |    
                SERVICE_CHANGE_CONFIG |    
                SERVICE_QUERY_STATUS |     
                SERVICE_ENUMERATE_DEPENDENTS |     
                SERVICE_START |     
                SERVICE_STOP |     
                SERVICE_PAUSE_CONTINUE |      
                SERVICE_INTERROGATE |     
                SERVICE_USER_DEFINED_CONTROL);    
            int SERVICE_AUTO_START = 0x00000002;   
            #endregion Constants declaration.    
            try    {    
                IntPtr sc_handle = OpenSCManager(null,null,SC_MANAGER_CREATE_SERVICE);   
                if (sc_handle.ToInt32() != 0)    
                {      
                    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);   
                    if(sv_handle.ToInt32() ==0)     
                    {     
                        CloseServiceHandle(sc_handle);     
                        return false;     
                    }    
                    else    
                    {     
                        //試嘗啓動服務    
                        int i = StartService(sv_handle,0,null);      
                        if(i==0)      
                        {       
                            return false; 
                        }      
                        CloseServiceHandle(sc_handle);     
                        return true;    
                    }    
                }    
                else     
                    return false;
            }    
            catch(Exception e)
  
            {    
                throw e;   
            } 
        }
 ///    
        /// 反安裝服務. 
        /// ///    
        /// 服務名.   
        public bool UnInstallService(string svcName)  
        {   
            int GENERIC_WRITE = 0x40000000;   
            IntPtr sc_hndl = OpenSCManager(null,null,GENERIC_WRITE);    
            if(sc_hndl.ToInt32() !=0)   
            {      int DELETE = 0x10000;  
                IntPtr svc_hndl = OpenService(sc_hndl,svcName,DELETE);   
                if(svc_hndl.ToInt32() !=0)    
                {      
                    int i = DeleteService(svc_hndl);  
                    if (i != 0)      
                    {       
                        CloseServiceHandle(sc_hndl);     
                        return true;     
                    }     
                    else    
                    {       
                        CloseServiceHandle(sc_hndl);     
                        return false;    
                    }    
                }    
                else  
                    return false;    
            }    
            else  
                return false; 
        }  

三.加載一個程序集,並運行其中的所有安裝程序。

view plaincopy to clipboardprint?
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 

 

發佈了58 篇原創文章 · 獲贊 4 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章