I am trying to get the windows event viewer logs for a specific source and time duration. But the GetEventLog method takes all the events into an array.
System.Diagnostics.EventLog.GetEventLoges(MachineName);
Is there is any way to get windows event log for a specific source and time like WindowsLog/System last 12 hr like filter present in event viewer.
You can try the following code to filter the specific time you want to search.
Like the following, I filtered the last two hours' events.
First, you need to add the Application Manifest file in your current project to have the permission to achieve the information about event log.
Then, please find the security tag and replace the following code.
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
Next, you can write the following code.
class Program
{
static void Main(string[] args)
{
EventLog log = new EventLog("Security");
var entries = log.Entries.Cast<EventLogEntry>()
.Where(x => x.TimeWritten>=DateTime.Now.AddHours(-1))
.Select(x => new
{
x.Site,
x.Source,
x.Message
}).ToList();
Console.WriteLine(entries.Count);
Console.ReadKey();
}
}
When you run your app, you will get the following mention and click restart.
You can get the event number in Eventviewer:
Then, this is the event number you get in console app:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.