C# 中有没有办法确定我是否有权启动和停止 Windows 服务?
如果我的进程在 NETWORK SERVICE 帐户下运行并且我尝试停止服务,我将收到“拒绝访问”异常,这很好,但我希望能够在尝试操作之前确定我是否被授权。
我正在尝试改进如下所示的代码:
var service = new ServiceController("My Service");
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
类似于:
if (AmIAuthorizedToStopWindowsService())
{
var service = new ServiceController("My Service");
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
}
更新 这样的事情怎么样:
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;
}
}