NealWalters NealWalters - 1 year ago 160
C# Question

C# get date/time a windows service started

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

I'm using this code now to check the status of services:

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

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

Reason: I'm writing a little BizTalk Monitor, and a common problem is that people often forget to restart the BizTalk Service (host instances) after doing a deploy. I want to show the time it last was started.

Answer Source

In a C# app, write

 using System.Diagnostics;
 private static DateTime GetStartTime(string processName)
    Process[] processes = 
    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 processname is not running, this throws an exception, modify to implement whatever alternative behavior you want. Also, if multiple instances of this process are running, this returns when the earliest was started...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download