Wednesday, June 3, 2009

EventViewer using C# Code

This code display the last error, warning and Information that register in the Event log of the local system.

Include the namespace
using System.Diagnostics;

Copy the below code into main method of the console program and while running program you have to enter the numerical value from 1 to 3. Base on the selection the last registered value is display from the EventLog Entry

you can check it under the control panel ==> Administrative Tools ==> EventViewer


String myEventType = null;
// Associate the instance of 'EventLog' with local System Log.
EventLog myEventLog = new EventLog("Application", ".");
Console.WriteLine("1:Error");
Console.WriteLine("2:Information");
Console.WriteLine("3:Warning");
Console.WriteLine("Select the Event Type");
int myOption = Convert.ToInt32(Console.ReadLine());
switch (myOption)
{
case 1: myEventType = "Error";
break;
case 2: myEventType = "Information";
break;
case 3: myEventType = "Warning";
break;
default: break;
}
EventLogEntryCollection myLogEntryCollection = myEventLog.Entries;
int myCount = myLogEntryCollection.Count;
// Iterate through all 'EventLogEntry' instances in 'EventLog'.
for (int i = myCount - 1; i > 0; i--)
{
EventLogEntry myLogEntry = myLogEntryCollection[i];
// Select the entry having desired EventType.
if (myLogEntry.EntryType.ToString().Equals(myEventType))
{
// Display Source of the event.
Console.WriteLine(myLogEntry.Source
+ " was the source of last event of type "
+ myLogEntry.EntryType);
Console.ReadLine();
return;
}
}


Enjoy :)

No comments:

Post a Comment