Searching Recent Event Logs with C#

Hi guys,

Today I was looking into event log searching. I run a script that does a chkdsk on reboot but then when the machine boots I want to see the log from that report.

To do this, I search the registry for the most recent event within a certain time period (I choose 1 day). We can use Linq to make the filtering quite easy.

EventLog el = new EventLog();
el.Log = log;
el.MachineName = ".";

var result = (from EventLogEntry elog in el.Entries
where (elog.TimeGenerated >= DateTime.Now - new TimeSpan(days, 0, 0, 0))
&& (elog.Source.ToString().Equals(source))
&& (elog.EventID == id)
orderby elog.TimeGenerated descending
select elog).First();
catch (InvalidOperationException)
Console.WriteLine("No results found. ");

Cheers to StackOverflow for the basis of this code.