4

有没有办法获取服务上次在 C# 中启动的日期/时间?

我现在正在使用此代码来检查服务的状态:

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

我可以用这个对象做吗?还是需要 WMI?

原因:我正在编写一个小 BizTalk Monitor,一个常见的问题是人们在部署后经常忘记重新启动 BizTalk Service(主机实例)。我想显示上次启动的时间。

4

3 回答 3

7

在 C# 应用程序中,编写

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

如果 processname 未运行,则会引发异常,请修改以实现您想要的任何替代行为。此外,如果此进程的多个实例正在运行,则它会在最早开始时返回...

于 2009-12-18T15:47:42.327 回答
2

这应该为您进行正确的查找。根据需要修改!

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;
            }
        }
于 2009-12-18T16:21:56.550 回答
1

考虑到此信息在服务管理器中不可见,它可能无法通过ServiceController类找到(我也没有在其中看到任何内容)。

话虽如此,请尝试查看Event Log。启动和停止服务时会自动生成一个事件。

于 2009-12-18T15:43:37.250 回答