我正在尝试开发一个 Windows 应用程序来启动/停止和监视两个特定服务的状态。
问题是我得到
System.ComponentModel.Win32Exception:访问被拒绝
请注意,这两个服务都是本地系统
以下是我的代码
private void StartService(string WinServiceName)
{
ServiceController sc = new ServiceController(WinServiceName,".");
try
{
if (sc.ServiceName.Equals(WinServiceName))
{
//check if service stopped
if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Stopped))
{
sc.Start();
}
else if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Paused))
{
sc.Start();
}
}
}
catch (Exception ex)
{
label3.Text = ex.ToString();
MessageBox.Show("Could not start " + WinServiceName + "Service.\n Error : " + ex.ToString(), "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
sc.Close();
sc.Dispose();
// CheckStatus();
}
}