System.ComponentModel.Win32Exception:拒绝访问错误

我正在使用c#代码启动和停止窗口服务,但我收到此错误。

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(); } } 

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

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

应用程序池

以管理员模式运行VS并加载项目。以管理员模式打开开发人员VS cmd。使用计算机域名(如domainname \ username.Hope)使用正确的用户名。