C#_EventLog Exception

138 views Asked by At

I’m trying to write a simple event log but i confront with “System.Security.SecurityException: The source was not found...” and i searched a lot but couldn’t find an efficient solution, I really really appreciate if someone help me with that I know that the source needed to be created and the key must be registered but what is the key and How should i do that?

String source =“DemoTestApplication”;
String log = “DemoEventLog”;
EventLog demolog=new EventLog(log);
EventLog demolog=new EventLog(log);
demolog.Source=source;
demolog.writeEntry(“This is the first message to the log”,EventLogEntryType.Information);
1

There are 1 answers

0
Polyfun On

Try this:

public static void LogEvent(string logBuffer, EventLogEntryType eventLogEntryType)
{
    const string source = "DemoTestApplication";

    // The user may not have permissions to access any event logs, therefore catch any SecurityExceptions.
    try
    {
        if (!EventLog.SourceExists(source))
        {
            // This requires administrator privileges.
            EventLog.CreateEventSource(source, "Application");
        }
        using (EventLog eventLog = new EventLog())
        {
            eventLog.Source = source;
            eventLog.WriteEntry(logBuffer, eventLogEntryType);
        }
    }
    catch (System.Security.SecurityException ex)
    {
        // Source was not found, but some or all of the event logs could not be searched.
        // May occur e.g., when trying to search Security event log.
        // EventLog.CreateEventSource requires permission to read all event logs to make sure 
        // that the new source name is unique.
        Debug.WriteLine(logBuffer);
        Debug.WriteLine(ex.ToString());
    }
}

Generally it is better to create the event log source when running with administrator/elevated privileges, e.g., during installation of your software.