Unable to restart windows service from my ASP.NET application
I am trying to restart Windows Time Service from my asp.net application using the following code but it always return s a TimeoutException. I have tried various ways to remove this error and restart the service but unfortunately fails in it. The code which i am using for this purpose is shown below:
private ServiceController service =
new ServiceController( "W32Time", Environmen开发者_如何转开发t.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 );
}
}
I am using Windows 7. Can anyone suggest me a solution for this problem? Any help will be appreciated.
Your example works just fine for me with the VS built-in web server.
Which leads me think that the user which your web app run under does not have permission to start/stop services. This would either be the AppPool user or your logged in user depending on how the app is configured.
精彩评论