windows服務大家都不陌生,windows服務組的概念,貌似ms并沒有這個說法。
作為一名軟件開發者,我們的機器上安裝有各種開發工具,伴隨著各種相關服務。
visual studio可以不打開,sqlserver management studio可以不打開,但是sqlserver服務卻默認開啟了。下班后,我的計算機想用于生活、娛樂,不需要數據庫服務這些東西,尤其是在安裝了oracle數據庫后,我感覺機器吃力的很。
每次開機后去依次關閉服務,或者設置手動開啟模式,每次工作使用時依次去開啟服務,都是一件很麻煩的事情。因此,我講這些相關服務進行打包,打包為一個服務組的概念,并通過程序來實現服務的啟動和停止。
這樣我就可以設置sqlserver、oracle、vmware等的服務為手動開啟,然后在需要的時候選擇打開。
以上廢話為工具編寫背景,也是一個應用場景描述,下邊附上代碼。
服務組的定義,我使用了ini配置文件,一個配置節為一個服務器組,配置節內的key、value為服務描述和服務名稱。
配置內容的先后決定了服務開啟的順序,因此類似oracle這樣的對于服務開啟先后順序有要求的,要定義好服務組內的先后順序。
value值為服務名稱,服務名稱并非services.msc查看的名稱欄位的值,右鍵服務,可以看到,顯示的名稱其實是服務的顯示名稱,這里需要的是服務名稱。
配置文件如下圖所示
注:ini文件格式:
[section1]
key1=value1
key2=value2
程序啟動,主窗體加載,獲取配置節,即服務組。
1
2
3
|
string path = directory.getcurrentdirectory() + "/config.ini" ; list< string > servicegroups = inihelper.getallsectionnames(path); cboservicegroup.datasource = servicegroups; |
其中的ini服務類,參考鏈接:c#操作ini文件的輔助類inihelper
服務的啟動和停止,需要引入system.serviceprocess程序集。
啟動服務組:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
if ( string .isnullorempty(cboservicegroup.text)) { messagebox.show( "請選擇要操作的服務組" ); return ; } // string path = directory.getcurrentdirectory() + "/config.ini" ; string section = cboservicegroup.text; string [] keys; string [] values; inihelper.getallkeyvalues(section, out keys, out values, path); // foreach ( string value in values) { servicecontroller sc = new servicecontroller(value); // try { servicecontrollerstatus scs = sc.status; if (scs != servicecontrollerstatus.running) { try { sc.start(); } catch (exception ex) { messagebox.show( "服務啟動失敗\n" + ex.tostring()); } } } catch (exception ex) { messagebox.show( "不存在服務" + value); } // } // messagebox.show( "服務啟動完成" ); |
停止服務組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
if ( string .isnullorempty(cboservicegroup.text)) { messagebox.show( "請選擇要操作的服務組" ); return ; } // string path = directory.getcurrentdirectory() + "/config.ini" ; string section = cboservicegroup.text; string [] keys; string [] values; inihelper.getallkeyvalues(section, out keys, out values, path); // foreach ( string value in values) { servicecontroller sc = new servicecontroller(value); try { servicecontrollerstatus scs = sc.status; if (scs != servicecontrollerstatus.stopped) { try { sc.stop(); } catch (exception ex) { messagebox.show( "服務停止失敗\n" + ex.tostring()); } } } catch (exception ex) { messagebox.show( "不存在服務" + value); } // } // messagebox.show( "服務停止完成" ); } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/mahongbiao/p/3762437.html