c#开启/停止Windows服务

需要管理员权限运行才行,不用多说,详见代码

using System;
using System.Collections.Generic;
using System.Text;

namespace StartWindowsServiceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string windowsServiceName = "iphlpsvc";
            StartWindowsService(windowsServiceName);
            StopWindowsService(windowsServiceName);

            Console.Read();
        }

        /// 
        /// 开启服务
        /// 
        /// 服务名称
        static void StartWindowsService(string windowsServiceName)
        {
            using (System.ServiceProcess.ServiceController control = new System.ServiceProcess.ServiceController(windowsServiceName))
            {
                if (control.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
                {
                    Console.WriteLine("服务启动......");
                    control.Start();
                    Console.WriteLine("服务已经启动......");
                }
                else if(control.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    Console.WriteLine("服务已经启动......");
                }
            }

        }

        /// 
        /// 停止服务
        /// 
        /// 服务名称
        static void StopWindowsService(string windowsServiceName)
        {
            using (System.ServiceProcess.ServiceController control = new System.ServiceProcess.ServiceController(windowsServiceName))
            {
                if (control.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    Console.WriteLine("服务停止......");
                    control.Stop();
                    Console.WriteLine("服务已经停止......");
                }
                else if (control.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
                {
                    Console.WriteLine("服务已经停止......");
                }
            }
        }
    }
}

你可能感兴趣的:(.Net,windows服务,windows,服务)