Note that there are some explanatory texts on larger screens.

plurals
  1. POAm I authorized to start/stop windows services?
    primarykey
    data
    text
    <p>Is there a way in C# to determine if I am authorized to start and stop windows services?</p> <p>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.</p> <p>I am trying to improve code that looks like this:</p> <pre><code>var service = new ServiceController("My Service"); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); </code></pre> <p>to something like:</p> <pre><code>if (AmIAuthorizedToStopWindowsService()) { var service = new ServiceController("My Service"); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); } </code></pre> <p><strong>UPDATE</strong> What about something like this:</p> <pre><code>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 =&gt; s.ServiceName.In(wellKnownServices) &amp;&amp; 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; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload