Thursday, August 19, 2010

Handling windows services from the code(c#)..........

Wondering how to start, stop, or to get the status of the windows services which are available at SERVICES.MSC.


ASPX CODE:
----------------


.CS code:
-------------

protected void btnStatus_Click(object sender, EventArgs e)
{//declaring the variables
ServiceController scObj = null;
try
{
//creating the object for the service cotroller.
scObj = new ServiceController();
//the service name can be viewed from the: goto RUN->SERVICES.MSC->select a //service->properties->service name.
scObj.ServiceName = "AppHostSvc";

//for stopped state
if (scObj.Status == ServiceControllerStatus.Stopped)
{
lblMsgg.Text = "The service is stopped";
//now we are starting the service
scObj.Start();
}//for running state
else if (scObj.Status == ServiceControllerStatus.Running)
{
lblMsgg.Text = "The service is running.";
//now we are stopping the service
scObj.Stop();
}//for paused state
else if (scObj.Status == ServiceControllerStatus.Paused)
{
lblMsgg.Text = "The service is Paused.";
}

}
catch (Exception Ex)
{
throw Ex;
}
finally
{//clearing the memory
if (scObj != null) scObj = null;
}
}

1 comment:

  1. please make sure the comments are in a same line.......if they are coming in the next line due to the space available for pasting the code here......please comment the lines which are comments

    ReplyDelete