Search code examples
c#wpfevent-log

C# - EventLogSession.ExportLog method throws EventLogNotFoundException in WPF application


I'm trying to implement a feature in a .NET Framework 4.7.2 WPF application which would allow customers to export their local application event log as part of a diagnostics package. I wrote this method:

/// <summary>
/// Exports only errors from local application event log
/// </summary>
void addWindowsEventLog(String exportPath) {
    const String QUERY_ERRORS = "*[System/Level=2]";
    using (var eventLogSession = new EventLogSession()) {
        eventLogSession.ExportLog("Application", PathType.LogName, QUERY_ERRORS, exportPath);
    }
}

For some reason it's failing with this exception:

System.Diagnostics.Eventing.Reader.EventLogNotFoundException
   at System.Diagnostics.Eventing.Reader.EventLogException.Throw(Int32)
   at System.Diagnostics.Eventing.Reader.NativeWrapper.EvtExportLog(System.Diagnostics.Eventing.Reader.EventLogHandle, System.String, System.String, System.String, Int32)

Event log not found? I'm targetting the Application log, which clearly exists and I set PathType parameter to LogName. What gives?

  • I've verified that I'm passing a fully-qualified file path for exportPath and that the directory exists.
  • This application always runs in an administrative context, so it doesn't appear to be a rights issue.
  • Interestingly, though, the issue isn't reproducible in a simple console application.

According to the stack trace, the exception is being thrown by Win32 native function EvtExportLog.


Solution

  • The issue isn't in the code, but in parameter values, specifically in targetFilePath parameter:

    1. Ensure that destination directory path exist. This method doesn't create missing directories.
    2. Ensure that destination file does not exist. This method cannot overwrite existing file.
    3. Ensure that you are passing full path to a file. This method doesn't support relative paths and environment variables.

    The EventLogNotFoundException isn't necessary related to first path parameter, it can be related to targetFilePath parameter too. And I suspect that this is the case.