How to check windows service status using ASP.NET

 How to check windows service status using ASP.NET

Here I am going to explain you how to check windows service status from a web application?

This will be usefull when you have to monitor any important windows service remotely without login to the system.


Below is the .aspx page.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Service.aspx.cs" Inherits="Service" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblService" runat="server" Text="Service Name"></asp:Label>
        <asp:TextBox ID="txtServiceName" runat="server"></asp:TextBox>
        <asp:Button ID="btnCheckStatus" runat="server" OnClick="btnCheckStatus_Click" Text="Check Service Status" /><br />
        <asp:Label ID="lblStatus" runat="server"></asp:Label></div>
    </form>
</body>
</html>

And below is the .cs file

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ServiceProcess;

public partial class Service : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
     protected void btnCheckStatus_Click(object sender, EventArgs e)
    {
        string strServiceName = txtServiceName.Text;
        string strStatus = string.Empty;
        try
        {
            strStatus = "Undefined";
            System.ServiceProcess.ServiceController[] services;
            services = System.ServiceProcess.ServiceController.GetServices();
            for (int i = 0; i < services.Length; i++)
            {
                if (services[i].ServiceName == strServiceName)
                {
                    strStatus = services[i].Status.ToString();
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            lblStatus.Text = ex.Message.ToString(); ;
        }
        lblStatus.Text= strStatus;
    }
}


Keep in mind that You have to add service reference to use System.Serviceprocess in order to use System.ServiceProcess

No Comments