C#对Windows服务组的启动与停止操作

时间:2019-04-13
本文章向大家介绍C#对Windows服务组的启动与停止操作,主要包括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

程序启动,主窗体加载,获取配置节,即服务组。

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

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