Example #1
0
        /// <summary>
        /// 将服务设置为 自动启动,并启动未启动的服务
        /// </summary>
        /// <param name="service"></param>
        public static void StartService(ServiceController service)
        {
            if (service == null)
            {
                return;
            }

            try
            {
                if (WinSrvHelper.GetStartupType(service) != "AUTOMATIC")
                {
                    ChangeStartMode(service, ServiceStartMode.Automatic);  // 将服务设置为 自动启动
                }

                if (service.Status == ServiceControllerStatus.Running) // 已启动的服务不能再次启动
                {
                    return;
                }

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running);
            }
            catch (Exception ex)
            {
                NLogHelper.Error(ex);
            }
        }
Example #2
0
        public static void SafeChangeStartMode(string serviceName, ServiceStartMode mode)
        {
            ServiceController service = GetService(serviceName);

            if (service == null)
            {
                return;
            }

            string strMode = mode.ToString().ToUpper().TrimStart("SERVICESTARTMODE.");

            try
            {
                if (WinSrvHelper.GetStartupType(service) != strMode)
                {
                    ChangeStartMode(service, mode);  // 将服务设置为 自动启动
                }
            }
            catch (Exception ex)
            {
                NLogHelper.Error(ex);
            }
        }