2013-01-07 178 views
11

我正在使用C#代码来启动和停止窗口服务,但我收到此错误。System.ComponentModel.Win32Exception:访问被拒绝错误

System.ComponentModel.Win32Exception: Access is denied 

请帮帮我。

我的代码:

public void StartService(string serviceName, int timeoutMilliseconds) 
    { 
     ServiceController service = new ServiceController(serviceName); 
     try 
     { 
      TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); 

      service.Start(); 
      service.WaitForStatus(ServiceControllerStatus.Running, timeout); 
      lblMessage.Text = "Service Started."; 
     } 
     catch (Exception ex) 
     { 
      //lblMessage.Text = "Error in Service Starting."; 
      lblMessage.Text = ex.ToString(); 
     } 
    } 
+1

您确定该用户帐户具有启动服务所需的权限吗?你可以发布堆栈跟踪吗? –

+0

请参阅此处:http://stackoverflow.com/questions/6070295/starting-a-service-in-asp-net-c-with-the-right-permissions –

+0

堆栈跟踪是System.InvalidOperationException:无法打开aspnet_state服务于电脑'。'。 ---> System.ComponentModel.Win32Exception:访问被拒绝---内部异常堆栈跟踪结束---在System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess)上System.ServiceProcess.ServiceController.Start(String [] args )在System.ServiceProcess.ServiceController.Start()_Default.StartService(String serviceName,Int32 timeoutMilliseconds) – Mahesh

回答

10

让您的服务器上确保您的应用程序池标识帐户有权启动该服务。它适用于您的ASP.NET开发服务器,因为它在您的用户帐户下运行(admin) 在默认的IIS配置中,此帐户是网络服务或ApplicationPoolIdentity(取决于IIS版本),通常无法管理服务。

因此,更改IIS管理器中的池帐户(应用程序池/ NameOfYourYourPool /高级设置)。 您可以使用内置帐户或使用您的某个域名。

apppool

3

在管理员模式下运行VS并加载您project.Open开发者VS与计算机域名如域名\ username.Hope它会工作管理员mode.Give正确的用户名CMD。