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