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
程序啟動,主窗體加載,獲取配置節,即服務組。
string path = Directory.GetCurrentDirectory() + "/config.ini"; List<string> serviceGroups = INIHelper.GetAllSectionNames(path); cboServiceGroup.DataSource = serviceGroups;
其中的INI服務類,參考鏈接:C#操作INI文件的輔助類IniHelper
服務的啟動和停止,需要引入System.ServiceProcess程序集。
啟動服務組:
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("服務啟動完成");
停止服務組
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("服務停止完成");}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答