C # get date / time when windows service is running

Is there any way to get the date / time that the service started in C #?

I use this code to check the status of services:

ServiceController sc = new ServiceController(serviceName); // check sc.status for "Running" etc... with a Switch statement... 

Can I do this with this object? Or do you need WMI?

Cause. I am writing a small BizTalk monitor. A common problem is that people often forget to restart the BizTalk service (host instances) after deployment. I want to show the time when it was launched.

+4
source share
3 answers

In a C # application write

  using System.Diagnostics; private static DateTime GetStartTime(string processName) { Process[] processes = Process.GetProcessesByName(processName); if (processes.Length == 0) throw new ApplicationException(string.Format( "Process {0} is not running.", processName)); // ----------------------------- DateTime retVal = DateTime.Now; foreach(Process p in processes) if (p.StartTime < retVal) retVal = p.StartTime; return retVal ; } 

if the process name is not running, it throws an exception, modifying to implement any alternative behavior that you want. Also, if multiple instances of this process are running, it returns when the earliest was running ...

+6
source

This should do the right search for you. Change if necessary!

 public List<Hashtable> GetEventEntryByEvent( ref string logName, ref string machineName, ref string source) { try { //Create our list List<Hashtable> events = new List<Hashtable>(); //Connect to the EventLog of the specified machine EventLog log = new EventLog(logName, machineName); //Now we want to loop through each entry foreach (EventLogEntry entry in log.Entries) { //If we run across one with the right entry source // we create a new Hashtable // then we add the Message,Source, and TimeWritten values // from that entry if (entry.Source == source) { Hashtable entryInfo = new Hashtable(); entryInfo.Add("Message", entry.Message); entryInfo.Add("InstanceId", entry.InstanceId); entryInfo.Add("Source", entry.Source); entryInfo.Add("TimeWritten", entry.TimeWritten); // You can also replace TimeWritten with TimeGenerated //Add this new Hashtable to our list events.Add(entryInfo); entryInfo = null; } } //Return the results return events; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return null; } } 
+3
source

Given that this information is not displayed in the service manager, it probably cannot be found through the ServiceController class (and I did not see anything there).

At the same time, try to see the event log . An event is generated automatically when a service starts and stops.

+1
source

All Articles