Search code examples
c#.netevent-viewer

How to get the latest error details from the EventViewer log using c#?


I am using C# code to fetch the error message of a particular error from the eventviewer log file.

static void Main(string[] args)
    {
      EventLog myLog = new EventLog(); 
      myLog.Log = "Application";
      myLog.Source = "Application Error";
      foreach (System.Diagnostics.EventLogEntry entry in myLog.Entries)
      {
         if (entry.TimeGenerated == DateTime.Parse("9/19/2016 11:48:58 AM"))
            {
               using (StreamWriter writer = File.AppendText("Example.txt"))
            {
                writer.WriteLine(error_Message);
            }
       }
     }

This is my main function where I am getting the error message of a particular error in my Application log and I am printing the error message in a text file. So instead of accessing the error with the datetime, I want to access the latest error in the logfile.How can I get the last entered error in the logfile?Thanks in advance.


Solution

  • EventLog myLog = new EventLog(); 
    myLog.Log = "Application";
    myLog.Source = "Application Error";
    
    var lastEntry = myLog.Entries[myLog.Entries.Count-1];
    var last_error_Message = lastEntry.Message;
    
    for(int index=myLog.Entries.Count-1; index>0;index--)
    {
        var errLastEntry = myLog.Entries[index];
        if (errLastEntry.EntryType == EventLogEntryType.Error)
        {
            //this is the last entry with Error
            var appName = errLastEntry.Source;
            break;
        }
    }