本文主要说明了Windows服务的安装、卸载、启动、停止、获取服务安装路径、获取服务状态、检查服务是否存在、获取服务版

时间:2021-12-01 04:58:34

本文主要说明了Windows处事的安置、卸载、启动、遏制、获取处事安置路径、获取处事状态、检查究事是否存在、获取处事版本。

我们需要引用定名空间
using System.Configuration.Install;
using System.ServiceProcess;

    

/// <summary>  

/// 获取处事安置路径  

/// </summary>  

/// <param name="ServiceName"></param>  

/// <returns></returns>  

public static string GetWindowsServiceInstallPath(string ServiceName)  

        {  

string key = @"SYSTEM\CurrentControlSet\Services\" + ServiceName;  

string path = Registry.LocalMachine.OpenSubKey(key).GetValue("ImagePath").ToString();  

//替换失双引号    

            path = path.WordStr("\"", string.Empty);  

            FileInfo fi = new FileInfo(path);  

return fi.Directory.ToString()+"\\";  

        }  

/// <summary>  

/// 按照处事名称获取处事状态。  

/// </summary>  

/// <param name="serviceName">处事名</param>  

/// <returns>状态</returns>  

public static EnumServiceStatus GetServiceStatus(string serviceName)  

        {  

            EnumServiceStatus status=EnumServiceStatus.CannotGet;  

            System.ServiceProcess.ServiceController[] scs;  

            scs = System.ServiceProcess.ServiceController.GetServices();  

foreach (System.ServiceProcess.ServiceController sc in scs)  

            {  

if (serviceName.ToUpper() == sc.ServiceName.ToUpper())  

                {  

switch (sc.Status)  

                    {  

case System.ServiceProcess.ServiceControllerStatus.Stopped:  

                            status = EnumServiceStatus.Stopped;  

break;  

case System.ServiceProcess.ServiceControllerStatus.StartPending:  

                            status = EnumServiceStatus.StartPending;  

break;  

case System.ServiceProcess.ServiceControllerStatus.Running:  

                            status = EnumServiceStatus.Running;  

break;  

case System.ServiceProcess.ServiceControllerStatus.StopPending:  

                            status = EnumServiceStatus.StopPending;  

break;  

case System.ServiceProcess.ServiceControllerStatus.PausePending:  

                            status = EnumServiceStatus.PausePending;  

break;  

case System.ServiceProcess.ServiceControllerStatus.Paused: