2009-12-18 31 views
4

有沒有辦法獲取服務最後在C#中啓動的日期/時間?C#獲取日期/時間窗口服務開始

我使用這個代碼現在檢查服務的狀態:

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

我可以用這個對象做呢?還是需要WMI?

原因:我正在寫一個小小的BizTalk Monitor,而且一個常見的問題是人們經常忘記在部署後重新啓動BizTalk服務(主機實例)。我想顯示它最後一次開始的時間。

回答

6

在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沒有運行,這會拋出一個異常,修改來實現你想要的任何替代行爲。此外,如果此進程的多個實例正在運行,則會在最早啓動時返回...

+1

這隻有在服務當前正在運行時纔有效。 – 2009-12-18 15:51:23

+0

是的,修正了 – 2009-12-18 15:53:37

+1

它仍然沒有回答這個問題,這正是我所掌握的。他要求瞭解「服務何時開始。」使用此方法,您只能找到服務當前正在運行的時間。 – 2009-12-18 15:55:58

1

考慮到這些信息在服務管理器中不可見,所以可能無法通過ServiceController類找到(我沒有在其中看到任何內容)。

這就是說,試試看Event Log。服務啓動和停止時會自動生成一個事件。

+0

-1他想要做的在C# – 2009-12-18 15:51:25

+0

@Roboto:http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx – 2009-12-18 15:53:14

+0

@喬恩:這個信息將是很好的答案。告訴他看事件日誌並不意味着使用System.Diagnostics.EventLog ...更好的答案甚至會包括代碼示例 – 2009-12-18 15:55:45

3

這應該會爲您進行適當的查找。根據需要修改!

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; 
      } 
     } 
相關問題