[.NET] : 设定Windows Service启动类型

 

前言 :

最近在处理应用程序安装的相关问题。
系统内有使用Window Time Service来完成时间同步的功能。

 

但在启动这个服务的时候。
却发现使用ManagementObject Class控制 WMI的这种方式,
无法将Windows Service启动类型设定为「自动(延迟开始)」。

 

使用Google搜寻之后,
找到了可以使用 Windows SC命令,来做Windows Service的管理。
并且这个方式,可以将Windows Service启动类型设定为「自动(延迟开始)」。

 

本篇文章简单纪录,
.NET应用程序如何使用Windows SC命令,来做Windows Service启动类型的设定。

 

方法 :

整个方法思路为
1. 执行一个隐形的 cmd.exe。
2. cmd.exe 呼叫 Windows SC命令来控制Windows Service启动类型。
3. 隐形的cmd.exe无法取得执行讯息,会无从判断执行错误。
  采用限制输入、资料验证、遇时处理等等方法,来尽量减少执行错误的机率。

 

下列的程序将上述动作封装为函式,
使用之前需要先加入System.ServiceProcess参考,直接呼叫即可设定Windows Service启动类型。

 

使用范例 :

1
SetWindowsServiceStartupType("w32time", StartupType.AutomaticDelayed);<br>

 

原始码 :

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
public enum StartupType
{
    Automatic,
    Manual,
    Disabled,
    AutomaticDelayed,
}
         
public static void SetWindowsServiceStartupType(String serviceName, StartupType startupType, int timeoutMilliseconds = 0)
{
    // ServiceName
    if (string.IsNullOrEmpty(serviceName) == true)
    {
        throw new ArgumentException("serviceName");
    }
 
    // StartType
    string startupTypeString = string.Empty;
    switch (startupType)
    {
        case StartupType.Automatic: startupTypeString = "auto"; break;
        case StartupType.Manual: startupTypeString = "demand"; break;
        case StartupType.Disabled: startupTypeString = "disabled"; break;
        case StartupType.AutomaticDelayed: startupTypeString = "delayed-auto"; break;
        default: throw new ArgumentException("startupType");
    }
 
    // TimeoutMilliseconds
    if (timeoutMilliseconds < 0)
    {
        throw new ArgumentException("timeoutMilliseconds");
    }
 
    // Check Existed
    bool isExisted = false;
    foreach (ServiceController serviceController in ServiceController.GetServices())
    {
        if (string.Compare(serviceController.ServiceName, serviceName, true) == 0)
        {
            isExisted = true;
            break;
        }
    }
    if (isExisted == false) throw new Exception("Service not existed.");
 
    // Execute    
    String result = string.Empty;
    using (System.Diagnostics.Process process = new System.Diagnostics.Process())
    {
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.Arguments = string.Format("/c sc config {0} start= {1}", serviceName, startupTypeString);
        process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        process.StartInfo.CreateNoWindow = false;
        process.Start();
        if (timeoutMilliseconds == 0)
        {                   
            process.WaitForExit();                  
        }
        else
        {
            if (process.WaitForExit(timeoutMilliseconds) == false)
            {
                process.Kill();
                throw new System.TimeoutException();
            }
        }
    }
}
posted @   Clark159  阅读(1206)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示