C# 启动windows 服务(通过cmd管理员方式和winform 方式)

参考来源:
https://www.jb51.net/article/32645.htm
https://www.cnblogs.com/appskyy/p/11019647.html (主要就是这个DOS CMD 调用DOS)
public class SystemServicesMSCHelper
    {
        public static void StartServicesByServiceName(string servicesName)
        {
            using (ServiceController sc = new ServiceController(servicesName))
            {
                if (sc.CanStop)//判断是否可以关闭
                {
                    try
                    {
                        sc.Stop();
                        sc.WaitForStatus(ServiceControllerStatus.Stopped);//服务停止了才继续下一步

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("停止服务失败:" + ex);
                    }
                }

                if (!sc.CanStop)//判断是否可以开启
                {
                    try
                    {
                        sc.Start();
                        sc.WaitForStatus(ServiceControllerStatus.Running);//服务运行了才继续下一步
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("启动服务失败:" + ex);
                    }
                }
                sc.Close();
                sc.Dispose();
            }


        }


        private static string CmdPath = @"C:\Windows\System32\cmd.exe";

        /// <summary>
        /// 通过管理员命令运行CMD启动服务
        /// </summary>
        /// <param name="serverName"></param>
        public static void RunCmdServicesByServerName(string serverName)
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                StartServicesByServiceName(serverName);
                System.Diagnostics.Process.Start(CmdPath, "/c sc Start " + serverName);
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = @"C:\Windows\System32\";
                startInfo.FileName = CmdPath;
                startInfo.Arguments = $"/c sc Start " + serverName;
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "RunAs";
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {

                }

            }
        }



    }

 

posted @ 2022-07-01 13:41  LuoCore  阅读(1075)  评论(0编辑  收藏  举报