我正在嘗試編寫一個應用程序和服務來監視給定的一組服務,並確保它們正在運行,並且b)根據特定條件,根據需要重新啓動它們。在Windows 7的代碼中停止/啓動服務
我一直遇到訪問被拒絕的錯誤。
如果我只是通過系統上的進程迭代,找到一個我希望像這樣:
foreach (ServiceController sc in ServiceController.GetServices())
{
if(sc.ServiceName == "MyServiceName")
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 60));
sc.Start();
}
}
我得到:
InnerException: System.InvalidOperationException
Message="Cannot open My Service service on computer '.'."
Source="System.ServiceProcess"
StackTrace:
at System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess)
at System.ServiceProcess.ServiceController.Stop()
at lib.ListServices() in D:\lib.cs:line 552
at lib.Init() in D:\lib.cs:line 56
InnerException: System.ComponentModel.Win32Exception
Message="Access is denied"
ErrorCode=-2147467259
NativeErrorCode=5
InnerException:
我試圖模擬一個用戶,我有試圖從另一個作爲系統服務運行的服務執行相同的代碼。這兩者實際上都不能影響服務。如果它開始了,我無法阻止它。如果停止,我無法啓動它。我知道這一切都與權限有關,我只是沒有找到實際上讓我控制服務的機制。
任何援助將不勝感激。