日期:2014-06-10  浏览次数:20477 次

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://www.cnblogs.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     try
18     {
19         ServiceControllerStatus scs = sc.Status;
20         if (scs != ServiceControllerStatus.Running)
21         {
22             try
23             {
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     try
17     {
18         ServiceControllerStatus scs = sc.Status;
19         if (scs != ServiceControllerStatus.Stopped)
20         {
21             try
22             {
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 }