我正在尝试开发一个Windows应用程序,以启动/停止和监视两个特定服务的状态。

问题是我得到

system.componentmodel.win32 exception:拒绝访问

请注意,这两种服务都是本地系统

以下是我的代码

private void StartService(string WinServiceName)
{
  ServiceController sc = new ServiceController(WinServiceName,".");
try
{
  if (sc.ServiceName.Equals(WinServiceName))
  {
  //check if service stopped
    if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Stopped))
    {
       sc.Start();
    }
    else if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Paused))
    {
        sc.Start();
    }
  }

}
catch (Exception ex)
{
  label3.Text = ex.ToString();
  MessageBox.Show("Could not start " + WinServiceName + "Service.\n Error : " + ex.ToString(), "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
   sc.Close();
   sc.Dispose();
   // CheckStatus();
}
}
有帮助吗?

解决方案

尝试Leppie在他的评论中提出的建议,如果它不起作用,则需要告诉我们哪一行抛出了例外 - 当您创建ServiceController,当您尝试启动它或其他地方时。

顺便说一句,您不应致电sc.start(),如果该服务被暂停,则应致电sc.continue()。

另外,使用可能是更好的主意 使用 构造比尝试/最后,这样:

private void StartService(string WinServiceName)
{
    try
    {
        using(ServiceController sc = new ServiceController(WinServiceName,"."))
        {
            if (sc.ServiceName.Equals(WinServiceName))
            {
                //check if service stopped
                if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Stopped))
                {
                   sc.Start();
                }
                else if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Paused))
                {
                    sc.Continue();
                }
            }
        }
    }
    catch (Exception ex)
    {
        label3.Text = ex.ToString();
        MessageBox.Show("Could not start " + WinServiceName + "Service.\n Error : " + ex.ToString(), "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

这样,您就无需致电sc.close()自己(顺便说一句,您需要致电Close Only Dispose是多余的 - 关闭文档:与服务中断开此ServiceController实例并释放了该实例分配的所有资源。)

编辑: alt text

右键单击Explorer中的EXE文件,然后选择作为管理员运行。在Windows 7中,除非您有UAC(用户访问控制)关闭,否则在明确要求/或要求这样做之前,您不会以管理员的身份运行程序。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top