When working with windows or web applications we might need to start and stop the service. In this article we discuss about how to start and how to stop the IIS service.
Open Microsoft Visual Studio 2013 => Create Windows Application and name it as CSharpStartStopIIS
Add two buttons and change the text for both buttons to “Start IIS” and “Stop IIS”. We have to use System.ServiceProcess.dll to work with Services. So add System.ServiceProcess.dll to application by right click on solution and select Add => select Reference… as shown below.
Add below code to start and stop the IIS service.
using System;
using System.ServiceProcess;
using System.Windows.Forms;
namespace CSharpStartStopIIS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
ServiceController iisService = new ServiceController("W3SVC");
if (iisService != null)
{
do
{
iisService.Refresh();
}
while (iisService.Status == ServiceControllerStatus.ContinuePending ||
iisService.Status == ServiceControllerStatus.PausePending ||
iisService.Status == ServiceControllerStatus.StartPending ||
iisService.Status == ServiceControllerStatus.StopPending);
if (iisService.Status == ServiceControllerStatus.Stopped)
{
iisService.Start();
iisService.WaitForStatus(ServiceControllerStatus.Running);
}
else
{
if (ServiceControllerStatus.Paused == iisService.Status)
{
iisService.Continue();
iisService.WaitForStatus(ServiceControllerStatus.Running);
}
}
iisService.Close();
}
}
private void btnStop_Click(object sender, EventArgs e)
{
ServiceController iisService = new ServiceController("W3SVC");
if (iisService != null)
{
do
{
iisService.Refresh();
}
while (iisService.Status == ServiceControllerStatus.ContinuePending ||
iisService.Status == ServiceControllerStatus.PausePending ||
iisService.Status == ServiceControllerStatus.StartPending ||
iisService.Status == ServiceControllerStatus.StopPending);
if (iisService.Status == ServiceControllerStatus.Running ||
iisService.Status == ServiceControllerStatus.Paused)
{
iisService.Stop();
iisService.WaitForStatus(ServiceControllerStatus.Stopped);
}
iisService.Close();
}
}
}
}
As shown above we are using ServiceController class of System.ServiceProcess namespace by passing IIS service W3SVC. We have to use Start() and Stop() methods of ServiceController class.