C# 无法从我的ASP.NET应用程序重新启动windows服务

C# 无法从我的ASP.NET应用程序重新启动windows服务,c#,windows-services,C#,Windows Services,我正在尝试使用以下代码从asp.net应用程序重新启动Windows时间服务,但它始终返回TimeoutException。我尝试了各种方法来删除此错误并重新启动服务,但不幸的是失败了。我为此目的使用的代码如下所示: private ServiceController service = new ServiceController( "W32Time", Environment.MachineName ); private TimeSpan timeout = TimeSpan.Fr

我正在尝试使用以下代码从asp.net应用程序重新启动Windows时间服务,但它始终返回TimeoutException。我尝试了各种方法来删除此错误并重新启动服务,但不幸的是失败了。我为此目的使用的代码如下所示:

private ServiceController service = 
     new ServiceController( "W32Time", Environment.MachineName );
private TimeSpan timeout = TimeSpan.FromMilliseconds( 35000 );//15000 was the old value

// Restart W32Time Service
private void RestartService( )
{
    try
    {
        // Stop service if it is running
        if( service.Status == ServiceControllerStatus.Running )
        {
            service.Stop( );
            service.WaitForStatus( ServiceControllerStatus.Stopped, timeout );
        }

        // Start service if it is stopped
        if( service.Status == ServiceControllerStatus.Stopped )
        {
            if (!(service.Status.Equals(ServiceControllerStatus.Stopped) || 
                  service.Status.Equals(ServiceControllerStatus.StopPending)))
            {
                service.Stop();
            }

            service.Start( );
            service.WaitForStatus( ServiceControllerStatus.Running, timeout );
        }
    }
    catch( Exception ex )
    {
        log.Error( "Error in restarting windows service.", ex );
    }
}

我正在使用Windows7。有人能给我一个解决这个问题的办法吗?任何帮助都将不胜感激。

您的示例在VS内置web服务器上运行良好


这让我认为运行web应用的用户没有启动/停止服务的权限。这可能是AppPool用户或您的登录用户,具体取决于应用程序的配置方式。

可能是UAC问题,我假设您的用户是以管理员身份运行的。如果你以管理员的身份启动VS,它会工作吗?不是,它不使用管理员权限,即当我以管理员的身份启动VS,然后从该VS运行web应用时