我是靠谱客的博主 害怕汉堡,这篇文章主要介绍C#对Windows服务组的启动与停止操作,现在分享给大家,希望可以做个参考。

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("服务停止完成"); }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持靠谱客。

最后

以上就是害怕汉堡最近收集整理的关于C#对Windows服务组的启动与停止操作的全部内容,更多相关C#对Windows服务组内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(127)

评论列表共有 0 条评论

立即
投稿
返回
顶部