C# get date/time a windows service started

11,263

Solution 1

In a C# app, 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 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...

Solution 2

Considering this information isn't visible in the Services Manager, it probably can't be found through the ServiceController class (and I didn't see anything in there either).

That being said, try looking at the Event Log. An event is generated automatically when a service is started and stopped.

Share:
11,263
NealWalters
Author by

NealWalters

My main expertise is Microsoft BizTalk (http://BizTalk-Training.com), but also delve into WCF, PowerShell and general C# issues quite often. I blog at http://MyLifeIsMyMessage.net

Updated on June 04, 2022

Comments

  • NealWalters
    NealWalters almost 2 years

    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.