[.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启动类型。

 

使用范例 :

SetWindowsServiceStartupType("w32time", StartupType.AutomaticDelayed);

 

原始码 :

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 @ 2012-01-04 13:59  Clark159  阅读(1191)  评论(0编辑  收藏  举报