Search code examples
c#conditional-statementsevent-log

Read event viewer entries


I want to read event entries from a certain custom event log at c# program, And to filter them by their description. Is there a way to do it? Or a way to get the entries as collection so I will be able to select from that by condition?


Solution

  • Try something like this:

           string queryString = string.Format("*[System[TimeCreated[@SystemTime>='{0}' and @SystemTime<='{1}']]]",
                DateTime.Now.Date.AddDays(-10).ToString("s"),
                DateTime.Now.Date.ToString("s"));
            var q = new EventLogQuery("Microsoft-Windows-User Profile Service/Operational", PathType.LogName, queryString);
            var r = new EventLogReader(q);
    
            var list = new List<EventRecord>(); 
    
            EventRecord er = r.ReadEvent();
            while (er != null) {
                list.Add(er);
                er = r.ReadEvent();
            }
    

    The filter is XPath and XQuery. If you want to learn about an events internal structure I found it best to read through the filter definition within eventvwr. Look into the XML-tab...