16

I am using C# code to start and stop the window serves but I am getting this error.

System.ComponentModel.Win32Exception: Access is denied

My code:

 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();
        }
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
Mahesh
  • 1,465
  • 4
  • 19
  • 23
  • 1
    Are you sure that the user account has the required permissions to start a service? Can you post the stack trace? – Dirk Vollmar Jan 07 '13 at 10:38
  • See also here: http://stackoverflow.com/questions/6070295/starting-a-service-in-asp-net-c-with-the-right-permissions – Dirk Vollmar Jan 07 '13 at 10:40
  • The Stack Trace is System.InvalidOperationException: Cannot open aspnet_state service on computer '.'. ---> System.ComponentModel.Win32Exception: Access is denied --- End of inner exception stack trace --- at System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess) at System.ServiceProcess.ServiceController.Start(String[] args) at System.ServiceProcess.ServiceController.Start() at _Default.StartService(String serviceName, Int32 timeoutMilliseconds) – Mahesh Jan 07 '13 at 13:14

2 Answers2

18

Make sure your application pool identity account on your server has permissions to start that service. It works on your ASP.NET Development Server because it runs under your user account (admin) In a default IIS configuration, this account is Network service or ApplicationPoolIdentity (depending on IIS version) and usually cannot manage services.

So, change the pool account in IIS Manager (Application Pools/NameOfYourYourPool/Advanced Settings). You can use a built-in account or use one of your domain.

apppool

Cybermaxs
  • 24,378
  • 8
  • 83
  • 112
5

Run your VS in administrator mode and load your project.Open developer VS cmd in administrator mode.Give proper username with computer domain name like domainname\username.Hope it will work.

priyesh jaiswal
  • 141
  • 2
  • 4