Reading and clearing a Windows Event Log with C# .NET

In this post we saw how to create a custom event log and here how to the write to the event log. We’ll briefly look at how to read the entries from an event log and how to clear them.

First let’s create an event log and put some messages to it:

string source = "DemoTestApplication";
string log = "DemoEventLog";
EventLog demoLog = new EventLog(log);
demoLog.Source = source;
demoLog.WriteEntry("First message", EventLogEntryType.Information, 101);
demoLog.WriteEntry("Hello!!", EventLogEntryType.Error, 980);
demoLog.WriteEntry("Bye", EventLogEntryType.Warning);
demoLog.WriteEntry("Long live Mondays", EventLogEntryType.Information, 200);
demoLog.WriteEntry("This is a demo", EventLogEntryType.Information, 250);

This is what it looks like in the Event Viewer:

Filling test event log

Reading from a log is also straightforward:

string log = "DemoEventLog";
EventLog demoLog = new EventLog(log);
EventLogEntryCollection entries = demoLog.Entries;
foreach (EventLogEntry entry in entries)
	Console.WriteLine("Level: {0}", entry.EntryType);
	Console.WriteLine("Event id: {0}", entry.InstanceId);
	Console.WriteLine("Message: {0}", entry.Message);
	Console.WriteLine("Source: {0}", entry.Source);
	Console.WriteLine("Date: {0}", entry.TimeGenerated);

…which gives the following output:

Reading from event log

Clearing a log is very easy:


…and the log entries are gone:

Cleared demo event log

You can view all posts related to Diagnostics here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

5 Responses to Reading and clearing a Windows Event Log with C# .NET

  1. Amitkumar Wankhede says:

    Thanks….It was very helpful to me for my work related stuff. Made my job easier.

  2. jass says:

    sir i want to clear windows logs files using C# code..??

  3. Fatih Kaplan says:

    hello, I want to make event viewer connection for /c#. I want to connect to the Event Viewer on the server. What should I do for it ? I want to receive information log on and log off.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: