Tuesday, September 13, 2022

Activate a Windows Service on the current machine

public static string ActivateHybridService(string machine)
{
try
{
List serviceList = new List();
List InterestedList = new List();


ServiceController[] services = ServiceController.GetServices(machine);

foreach (ServiceController service in services)
{

// check for service names
if( "Infrastructure.Email.WinService" == service.ServiceName || "Finance.Pricing.Navision" == service.ServiceName)
{
string currentStatus = service.Status.ToString();
if (currentStatus.Trim().ToLower() != "running")
{
// config flag : if auto-reset then automatically Start service // if (appSettings.AutoStart == "1") {
service.Start();

using (StreamWriter sw = new StreamWriter(@"C:\junk\ReplicatePLMServiceRestartInfo.txt", true))
{
sw.WriteLine(DateTime.Now);
sw.WriteLine(service.ServiceName + " was Auto-Started.");
}
return "Service was Auto-Started.";
}
}
}
}
}
catch (Exception err)
{
using (StreamWriter sw = new StreamWriter(@"C:\junk\ReplicatePLMServicesRestar.txt", true))
{
sw.WriteLine(err.Message);
sw.WriteLine((err.InnerException == null ? string.Empty : err.InnerException.Message) +
(err.StackTrace ?? string.Empty));
}
return err.Message;
}

return "OK";
}

No comments: