Trying to start a windows service from a windows application giving System.ComponentModel.Win32Exception: Access is denied
I am trying to develop a windows application to start/stop and monitor status of two particular services.
The problem is I am getting
System.ComponentModel.Win32Exception: Access is denied
Note that both services are local system
The following is my code
private void StartService(string WinService开发者_开发百科Name)
{
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();
}
}
Try what leppie suggested in his comment, if it doesn't work you need to tell us which line is throwing exception - when you're creating ServiceController, when you're trying to start it or somewhere else.
Btw, you shouldn't call sc.Start() if the service is paused, you should call sc.Continue().
Also, it is probably better idea to use using construct than try/finally, like this:
private void StartService(string WinServiceName)
{
try
{
using(ServiceController sc = new ServiceController(WinServiceName,"."))
{
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.Continue();
}
}
}
}
catch (Exception ex)
{
label3.Text = ex.ToString();
MessageBox.Show("Could not start " + WinServiceName + "Service.\n Error : " + ex.ToString(), "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
That way you don't need to call sc.Close() yourself (btw, you need to call Close only Dispose is redundant - Documentation for Close: Disconnects this ServiceController instance from the service and frees all the resources that the instance allocated.)
EDIT:
Right click on your exe file in Explorer and choose Run As Administrator. In Windows 7, unless you have UAC (User Access Control) turned off you're not running programs as administrator until you explicitly request/or you are asked to do so.
精彩评论