C# ASP.NET 控制windows服务的 开启和关闭 以及重启
用asp.net控制windows服务的开启与关闭
效果如图
代码
首页页面需要添加引用
页面的pageload中
实例化windows服务
protected void page_load(object sender, eventargs e)
{
//此处代码用于显示页面加载中的效果,可以无视。
clientscript.registerclientscriptblock(gettype(), "", initjavascript());
//实例化windows服务,lediptransfer为我自己写的windows服务,大家可以用
service = new servicecontroller("lediptransfer");
onload();
}
至于服务名称的获取,查看服务详情后复制显示名称即可。
用于显示页面当前服务的状态
private void onload()
{
//获取服务的运行状态
string state = service.status.tostring();
switch (state)
{
case "stopped":
lblstate.text = "服务已停止";
btnrestart.enabled = false;
btnstart.enabled = true;
btnstop.enabled = false;
break;
case "running":
lblstate.text = "服务运行中";
btnstart.enabled = false;
btnrestart.enabled = true;
break;
/* 以下服务状态仅供参考,除非服务启动很慢,一般不需进行如下设置
case "paused":
lblstate.text = "服务已暂停";
break;
case "startpending":
lblstate.text = "服务正在启动";
break;
case "stoppending":
lblstate.text = "服务正在停止";
break;
case "continuepending":
lblstate.text = "服务即将继续";
break;
case "pausepending":
lblstate.text = "服务即将暂停";
break;
* */
}
}
///<summary>
///启动服务
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protectedvoid btnstart_click(object sender,eventargs e)
{
service.start();
//等待服务到达运行状态
service.waitforstatus(servicecontrollerstatus.running);
clientscript.registerstartupscript(gettype(),"","window.location.href=window.location.href",true);
}
///<summary>
///停止服务
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protectedvoid btnstop_click(object sender,eventargs e)
{
service.stop();
service.waitforstatus(servicecontrollerstatus.stopped);
clientscript.registerstartupscript(gettype(),"","window.location.href=window.location.href",true);
}
///<summary>
///重启服务
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protectedvoid btnrestart_click(object sender,eventargs e)
{
//停止服务
service.stop();
service.waitforstatus(servicecontrollerstatus.stopped);
//启动服务
service.start();
service.waitforstatus(servicecontrollerstatus.running);
clientscript.registerstartupscript(gettype(),"","window.location.href=window.location.href",true);
}
asp.net 方式开启服务,都需要很高的权限,所以如果你权限不够是无法开启的。
在system.web 下面加 identiy 可以模拟用户具有管理员权限
<system.web>
<identity impersonate="true" username="用户名" password="密码" />
</system.web>