Handy Error Handling Code

I’m bookmarking this site: http://www.c-sharpcorner.com/UploadFile/scottlysle/EventAndErrorLogging1… It’s an easy cut and paste code for writing to the event viewer.

using System.Diagnostics;

public class EventLogger


public New()


//default constructor


Like the ErrorLogger.cs class, this class contains only a single function used to write directly to the event log: (modified to fit on this page)


//NAME: WriteToEventLog

//PURPOSE: Write to Event Log

//PARAMETERS: Entry – Value to Write

// AppName – Name of Client Application. Needed

// because before writing to event log, you must

// have a named EventLog source.

// EventType – Entry Type, from EventLogEntryType

// Structure e.g., EventLogEntryType.Warning,

// EventLogEntryType.Error

// LogNam1e: Name of Log (System, Application;

// Security is read-only) If you

// specify a non-existent log, the log will be

// created

//RETURNS: True if successful


public bool WriteToEventLog(string entry, string appName, EventLogEntryType eventType, string logName)


EventLog objEventLog = new EventLog();



if (!(EventLog.SourceExists(appName)))


EventLog.CreateEventSource(appName, LogName);


objEventLog.Source = appName;

objEventLog.WriteEntry(entry, eventType);

return true;


catch (Exception Ex)


return false;





Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s