4

サービスがC#で最後に開始された日付/時刻を取得する方法はありますか?

現在、このコードを使用してサービスのステータスを確認しています。

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

このオブジェクトでそれを行うことはできますか?または、WMIが必要ですか?

理由:私は小さなBizTalkモニターを作成していますが、一般的な問題は、展開後にBizTalkサービス(ホストインスタンス)を再起動するのを忘れることが多いことです。最後に開始した時刻を表示したいと思います。

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

この情報がServicesManagerに表示されないことを考えると、おそらくServiceControllerクラスでは見つけることができません(そして、そこにも何も表示されませんでした)。

そうは言っても、イベントログを見てみてください。サービスが開始および停止されると、イベントが自動的に生成されます。

于 2009-12-18T15:43:37.250 に答える