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 string path = Directory.GetCurrentDirectory() + "/config.ini";2 List<string> serviceGroups = INIHelper.GetAllSectionNames(path);3 cboServiceGroup.DataSource = serviceGroups;
其中的INI服務類,參考鏈接:http://m.survivalescaperooms.com/mahongbiao/p/3751153.html
服務的啟動和停止,需要引入System.ServicePRocess程序集。
啟動服務組:
1 if (string.IsNullOrEmpty(cboServiceGroup.Text)) 2 { 3 MessageBox.Show("請選擇要操作的服務組"); 4 return; 5 } 6 // 7 string path = Directory.GetCurrentDirectory() + "/config.ini"; 8 string section = cboServiceGroup.Text; 9 string[] keys;10 string[] values;11 INIHelper.GetAllKeyValues(section, out keys, out values, path);12 //13 foreach (string value in values)14 {15 ServiceController sc = new ServiceController(value);16 //17 try18 {19 ServiceControllerStatus scs = sc.Status;20 if (scs != ServiceControllerStatus.Running)21 {22 try23 {24 sc.Start();25 }26 catch (Exception ex)27 {28 MessageBox.Show("服務啟動失敗/n" + ex.ToString());29 }30 }31 }32 catch (Exception ex)33 {34 MessageBox.Show("不存在服務" + value);35 }36 // 37 }38 //39 MessageBox.Show("服務啟動完成");停止服務組
1 if (string.IsNullOrEmpty(cboServiceGroup.Text)) 2 { 3 MessageBox.Show("請選擇要操作的服務組"); 4 return; 5 } 6 // 7 string path = Directory.GetCurrentDirectory() + "/config.ini"; 8 string section = cboServiceGroup.Text; 9 string[] keys;10 string[] values;11 INIHelper.GetAllKeyValues(section, out keys, out values, path);12 //13 foreach (string value in values)14 {15 ServiceController sc = new ServiceController(value);16 try17 {18 ServiceControllerStatus scs = sc.Status;19 if (scs != ServiceControllerStatus.Stopped)20 {21 try22 {23 sc.Stop();24 }25 catch (Exception ex)26 {27 MessageBox.Show("服務停止失敗/n" + ex.ToString());28 }29 }30 }31 catch (Exception ex)32 {33 MessageBox.Show("不存在服務" + value);34 }35 //36 37 }38 //39 MessageBox.Show("服務停止完成");40 }新聞熱點
疑難解答