Search code examples
c#processwindows-services

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.


Solution

  • 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; }
        }
    }