protected void btnRestart_Click(object sender, EventArgs e)
{
ServiceController sc = new ServiceController( "wuauserv ");
sc.ServiceName = "localhost ";
switch (sc.Status)
{
case ServiceControllerStatus.StopPending:
case ServiceControllerStatus.Stopped:
sc.Refresh();
while (sc.Status != ServiceControllerStatus.Stopped)
{
sc.Refresh();
}
sc.Start();
break;
case ServiceControllerStatus.StartPending:
case ServiceControllerStatus.Running:
sc.Stop();
while (sc.Status != ServiceControllerStatus.Stopped)
{
sc.Refresh();
}
sc.Start();
break;
default:
sc.Start();
break;
}
}
}
{
ServiceController sc = new ServiceController( "wuauserv ");
sc.ServiceName = "localhost ";
switch (sc.Status)
{
case ServiceControllerStatus.StopPending:
case ServiceControllerStatus.Stopped:
sc.Refresh();
while (sc.Status != ServiceControllerStatus.Stopped)
{
sc.Refresh();
}
sc.Start();
break;
case ServiceControllerStatus.StartPending:
case ServiceControllerStatus.Running:
sc.Stop();
while (sc.Status != ServiceControllerStatus.Stopped)
{
sc.Refresh();
}
sc.Start();
break;
default:
sc.Start();
break;
}
}
}
网友回复:见:http://blog.youkuaiyun.com/zhoufoxcn/archive/2007/03/14/1528824.aspx
在项目中,非凡是安装项目中我们经常要判定一些服务是否启动(判定SQL Server是否启动最常见),在.net中我们如何判定指定的Windows服务是否启动呢?首先要知道Windows服务的显示名称,这里以IIS检测为例,我们知道IIS的显示名称是"IIS Admin",现在用下面的代码来判定IIS是否启动。
ServiceController[] service=ServiceController.GetServices();
bool isStart = false;
for (int i = 0; i < service.Length; i )
{
if (service[i].DisplayName.ToUpper().Equals("IIS Admin".ToUpper()))
{
if (service[i].Status == ServiceControllerStatus.Running)
{
isStart = true;
break;
}
}
}
if (isStart)
{
MessageBox.Show("服务已经启动");
}
else
{
MessageBox.Show("服务没启动");
}
bool isStart = false;
for (int i = 0; i < service.Length; i )
{
if (service[i].DisplayName.ToUpper().Equals("IIS Admin".ToUpper()))
{
if (service[i].Status == ServiceControllerStatus.Running)
{
isStart = true;
break;
}
}
}
if (isStart)
{
MessageBox.Show("服务已经启动");
}
else
{
MessageBox.Show("服务没启动");
}
在使用时别忘记导入System.ServiceProcess这个名称空间,一般情况下VS.net是不会自动导入的。
获取了ServiceController 实例之后就可以Stop()/Pause ()/Start ()了。
网友回复:在下也按照楼上各位的方法去试了,但是却提示错误,比如我想启动Telnet,运行时却提示:用户代码未处理InvalidOperationException 无法启动计算机“.”上的服务 Telnet.请各位指教一下,谢谢!!
网友回复:确实说的很不错。Mark下