Search code examples
c#linqwindows-serviceswindows-securityevent-viewer

get the latest windows Startup Login event data from event viewer using c#?


i am getting all information from windows security log and event viewer related to logon and logg off but i want only latest loggon event info from all information can you please apply some linq on that to get the top most Startup Login event info

here is my code what i am trying

      EventLog log = new EventLog()
        {
            Source = "Microsoft Windows security auditing.",
            Log = "Security"
        };
      foreach (EventLogEntry entry in log.Entries)
        {

            Console.WriteLine(entry.Message);
        }

can you make any foreach in lambda base to get only logon event that is the latest one


Solution

  • Here is a sample to get the latest "Logon (4624)" and "Special Logon (4672)"

      var log = new EventLog
      {
        Source = "Microsoft Windows security auditing.",
        Log = "Security"
      };
      var latestLogon =
        log.Entries.Cast<EventLogEntry>()
          .Where(entry => entry.InstanceId == 4624 || entry.InstanceId == 4672)
          .OrderByDescending(i => i.TimeWritten)
          .FirstOrDefault();