服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#版Windows服务安装卸载小工具

C#版Windows服务安装卸载小工具

2021-12-01 14:42韩天伟 C#

这篇文章主要为大家推荐了一款C#版Windows服务安装卸载小工具,小巧灵活的控制台程序,希望大家喜欢,感兴趣的小伙伴们可以参考一下

前言
 在我们的工作中,经常遇到Windows服务的安装和卸载,在之前公司也普写过一个WinForm程序选择安装路径,这次再来个小巧灵活的控制台程序,不用再选择,只需放到需要安装服务的目录中运行就可以实现安装或卸载。 

开发思路
1、由于系统的权限限制,在运行程序时需要以管理员身份运行
2、因为需要实现安装和卸载两个功能,在程序运行时提示本次操作是安装还是卸载  需要输入 1 或 2 
3、接下来程序会查找当前目录中的可执行文件并过滤程序本身和有时我们复制进来的带有vhost的文件,并列出列表让操作者选择(一般情况下只有一个)
4、根据用户所选进行安装或卸载操作
5、由于可能重复操作,需要递归调用一下
具体实现
首先们要操作服务,需要用  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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
using System;
using System.Collections;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
 
namespace AutoInstallUtil
{
  public class SystemServices
  {
    /// <summary>
    /// 打开系统服务
    /// </summary>
    /// <param name="serviceName">系统服务名称</param>
    /// <returns></returns>
    public static bool SystemServiceOpen(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {
          if (control.Status != ServiceControllerStatus.Running)
          {
            control.Start();
          }
        }
        return true;
      }
      catch
      {
        return false;
      }
    }
 
 
    /// <summary>
    /// 关闭系统服务
    /// </summary>
    /// <param name="serviceName">系统服务名称</param>
    /// <returns></returns>
    public static bool SystemServiceClose(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {
 
          if (control.Status == ServiceControllerStatus.Running)
          {
            control.Stop();
          }
        }
        return true;
      }
      catch
      {
        return false;
      }
    }
 
    /// <summary>
    /// 重启系统服务
    /// </summary>
    /// <param name="serviceName">系统服务名称</param>
    /// <returns></returns>
    public static bool SystemServiceReStart(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {
          if (control.Status == System.ServiceProcess.ServiceControllerStatus.Running)
          {
            control.Continue();
          }
        }
        return true;
      }
      catch
      {
        return false;
      }
    }
 
    /// <summary>
    /// 返回服务状态
    /// </summary>
    /// <param name="serviceName">系统服务名称</param>
    /// <returns>1:服务未运行 2:服务正在启动 3:服务正在停止 4:服务正在运行 5:服务即将继续 6:服务即将暂停 7:服务已暂停 0:未知状态</returns>
    public static int GetSystemServiceStatus(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {
          return (int)control.Status;
        }
      }
      catch
      {
        return 0;
      }
    }
 
    /// <summary>
    /// 返回服务状态
    /// </summary>
    /// <param name="serviceName">系统服务名称</param>
    /// <returns>1:服务未运行 2:服务正在启动 3:服务正在停止 4:服务正在运行 5:服务即将继续 6:服务即将暂停 7:服务已暂停 0:未知状态</returns>
    public static string GetSystemServiceStatusString(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {
          var status = string.Empty;
          switch ((int)control.Status)
          {
            case 1:
              status = "服务未运行";
              break;
            case 2:
              status = "服务正在启动";
              break;
            case 3:
              status = "服务正在停止";
              break;
            case 4:
              status = "服务正在运行";
              break;
            case 5:
              status = "服务即将继续";
              break;
            case 6:
              status = "服务即将暂停";
              break;
            case 7:
              status = "服务已暂停";
              break;
            case 0:
              status = "未知状态";
              break;
          }
          return status;
        }
      }
      catch
      {
        return "未知状态";
      }
    }
 
    /// <summary>
    /// 安装服务
    /// </summary>
    /// <param name="stateSaver"></param>
    /// <param name="filepath"></param>
    public static void InstallService(IDictionary stateSaver, string filepath)
    {
      try
      {
        var myAssemblyInstaller = new AssemblyInstaller
        {
          UseNewContext = true,
          Path = filepath
        };
        myAssemblyInstaller.Install(stateSaver);
        myAssemblyInstaller.Commit(stateSaver);
        myAssemblyInstaller.Dispose();
      }
      catch (Exception ex)
      {
        throw new Exception("installServiceError/n" + ex.Message);
      }
    }
 
    public static bool ServiceIsExisted(string serviceName)
    {
      ServiceController[] services = ServiceController.GetServices();
      return services.Any(s => s.ServiceName == serviceName);
    }
 
    /// <summary>
    /// 卸载服务
    /// </summary>
    /// <param name="filepath">路径和文件名</param>
    public static void UnInstallService(string filepath)
    {
      try
      {
        //UnInstall Service
        var myAssemblyInstaller = new AssemblyInstaller
        {
          UseNewContext = true,
          Path = filepath
        };
        myAssemblyInstaller.Uninstall(null);
        myAssemblyInstaller.Dispose();
      }
      catch (Exception ex)
      {
        throw new Exception("unInstallServiceError/n" + ex.Message);
      }
    }
  }
}

接下来我们封装控制台的操作方法为了实现循环监听这里用了递归 

?
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
 
namespace AutoInstallUtil
{
  class Program
  {
    static void Main(string[] args)
    {
      try
      {
        ServerAction();
      }
      catch (Exception ex)
      {
        Console.WriteLine("发生错误:{0}", ex.Message);
      }
 
      Console.ReadKey();
    }
 
    /// <summary>
    /// 操作
    /// </summary>
    private static void ServerAction()
    {
      Console.WriteLine("请输入:1安装 2卸载");
      var condition = Console.ReadLine();
      var currentPath = Environment.CurrentDirectory;
      var currentFileNameVshost = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName).ToLower();
      var currentFileName = currentFileNameVshost.Replace(".vshost.exe", ".exe");
      var files =
        Directory.GetFiles(currentPath)
          .Select(o => Path.GetFileName(o).ToLower())
          .ToList()
          .Where(
            o =>
              o != currentFileNameVshost
              && o != currentFileName
              && o.ToLower().EndsWith(".exe")
              && o != "installutil.exe"
              && !o.ToLower().EndsWith(".vshost.exe"))
          .ToList();
      if (files.Count == 0)
      {
        Console.WriteLine("未找到可执行文件,请确认当前目录有需要安装的服务程序");
      }
      else
      {
        Console.WriteLine("找到目录有如下可执行文件,请选择需要安装或卸载的文件序号:");
      }
      int i = 0;
      foreach (var file in files)
      {
        Console.WriteLine("序号:{0} 文件名:{1}", i, file);
        i++;
      }
      var serviceFileIndex = Console.ReadLine();
      var servicePathName = currentPath + "\\" + files[Convert.ToInt32(serviceFileIndex)];
      if (condition == "1")
      {
        SystemServices.InstallService(null, servicePathName);
      }
      else
      {
        SystemServices.UnInstallService(servicePathName);
      }
      Console.WriteLine("**********本次操作完毕**********");
      ServerAction();
    }
  }
}

到此为止简单的安装程序就写完了,为了醒目我选了个红色的西红柿来做为图标,这样显示些

源码和程序:安装卸载Windows服务

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

延伸 · 阅读

精彩推荐
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11