Is there a way in C# to determine if I am authorized to start and stop windows services?
If my process is running under the NETWORK SERVICE account and I attempt to stop a service I will get a "Access denied" exception, which is fine, but I would like to be able to determine if I am authorized before attempting the operation.
I am trying to improve code that looks like this:
var service = new ServiceController("My Service");
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
to something like:
if (AmIAuthorizedToStopWindowsService())
{
var service = new ServiceController("My Service");
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
}
UPDATE What about something like this:
private bool AutorizedToStopWindowsService()
{
try
{
// Try to find one of the well-known services
var wellKnownServices = new[]
{
"msiserver", // Windows Installer
"W32Time" // Windows Time
};
var services = ServiceController.GetServices();
var service = services.FirstOrDefault(s => s.ServiceName.In(wellKnownServices) && s.Status.In(new[] { ServiceControllerStatus.Running, ServiceControllerStatus.Stopped }));
// If we didn't find any of the well-known services, we'll assume the user is not autorized to stop/start services
if (service == null) return false;
// Get the current state of the service
var currentState = service.Status;
// Start or stop the service and then set it back to the original status
if (currentState == ServiceControllerStatus.Running)
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(5));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(5));
}
else
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(5));
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(5));
}
// If we get this far, it means that we successfully stopped and started a windows service
return true;
}
catch
{
// An error occurred. We'll assume it's due to the fact the user is not authorized to start and stop services
return false;
}
}