Adeel Yousafzai
Adeel Yousafzai

Reputation: 57

How to get pid of window service using its name and check if the process is running in task manager or not? using C#

I am trying to check if the program svchost is running which is actually Windows service.

If that service is not running, start it again. I mean if the user try to end the task from task manager start it again.

Upvotes: 0

Views: 1486

Answers (2)

Jonathan Applebaum
Jonathan Applebaum

Reputation: 5986

Update from previous answer:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Management;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = IsServiceActive("unstoppable");
            Console.WriteLine("PID: {0}, Status: {1}", data.Id, data.Status);
            Console.ReadLine();
        }

        private static SrvData IsServiceActive(string srvname)
        {
            string status = "NA";
            int id = -1;

            ServiceController[] srvc = ServiceController.GetServices();
            foreach (var sr in srvc)
            {
                if (sr.ServiceName == srvname)
                {
                    // get status
                    status = sr.Status.ToString();
                    // get id
                    ManagementObject wmiService;
                    wmiService = new ManagementObject("Win32_Service.Name='" + srvname + "'");
                    wmiService.Get();
                    id = Convert.ToInt32(wmiService["ProcessId"]);
                    break;
                }
            }

            SrvData result = new SrvData() { Id = id, Status = status };
            return result;
        }
    }

    public class SrvData
    {
        public string Status { get; set; }
        public int Id { get; set; }
    }
}

Upvotes: 1

Vivek Nuna
Vivek Nuna

Reputation: 1

You can do like this.

ServiceController sc = new ServiceController(ServiceName);
if (sc.Status == ServiceControllerStatus.Running)
{
//do something
}
else
{
    sc.Start();
}

I would say check for ServiceControllerStatus.Stopped status and then start the service.

and to answer your other question how to get PID.

int pid= Process.GetProcessesByName(ServiceName)[0].Id;

Upvotes: 1

Related Questions