C# ASP.NET 控制windows服务的 开启和关闭 以及重启

时间:2021-02-02 17:34:43

用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>