Search code examples
c#.netc#-4.0event-viewer

Create Custom XPath for Time Created


I am trying to to read the event logs which are generated after some specified time but it is giving Invalid query string exception.

I have followed msdn site how to provide xpaths and below is my implementation.What is wrong in my code.

var Date = "6/13/2017 3:51:10 PM";
        string queryString = "*[System/TimeCreated/@SystemTime >=" + Date + "]]";
        SecureString pw = GetPassword();

        EventLogSession session = new EventLogSession(
            "MachineName",                               // Remote Computer
            "DomainName",                                  // Domain
            "userName",                                // Username
            pw,
            SessionAuthentication.Default);

        pw.Dispose();
        EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryString);
        query.Session = session;

        try
        {
            EventLogReader logReader = new EventLogReader(query);
            for (EventRecord eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent())
            {
                var date = eventDetail.TimeCreated;
            }

            // Display event info
        }
        catch (EventLogException e)
        {
            Console.WriteLine("Could not query the remote computer! " + e.Message);
            return;
        }

Solution

  • In the XPath you have to do two things. First, you have to quote the date value because it is a string. Second, you have to use ISO format, because that is the format it is in.

     var Date = "2017-06-13T15:51:10Z";
     string queryString = "*[System/TimeCreated[@SystemTime >='" + Date + "']]";