利用Windows系统日志统计员工每天上下班考勤时间(命令行参数为统计月份):
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace ConsoleSysLogView { class Program { static void Main(string[] args) { SystemLog log = new SystemLog(); if (args.Length == 1) { int x = Convert.ToInt32(args[0]); log.PrintEventLog(x); } else { Console.WriteLine("Event count: " + log.Count); Console.WriteLine("QueryMessage: SysLogView.exe MonthNum"); } if (Debugger.IsAttached) Console.ReadKey(); } } public class SystemLog { private EventLogEntryCollection _eventCollection; private EventLog _systemEvent; public SystemLog() { _systemEvent = new EventLog(); _systemEvent.Log = "System"; _eventCollection = _systemEvent.Entries; } public void PrintEventLog(int month) { DateTime dateFrom = new DateTime(DateTime.Now.Year, month, 1); DateTime dateTo = dateFrom.AddMonths(1); DateTime dt = dateFrom; while (dt < dateTo) { IList<EventLogEntry> list = Events.Where(a => a.TimeGenerated.Date == dt.Date).OrderBy(a => a.TimeGenerated).ToList(); if (list.Count > 0) { Console.WriteLine(); Console.WriteLine(GetLogEntryText(list[0])); if (list.Count > 1) { int l = list.Count - 1; Console.WriteLine(GetLogEntryText(list[l])); } } dt = dt.AddDays(1); } } private string GetLogEntryText(EventLogEntry entry) { return string.Format("{0} {1:yyyy-MM-dd HH:mm} 来源:{2} 事件ID:{3}", entry.EntryType, entry.TimeGenerated.ToString("yyyy-MM-dd HH:mm"), entry.Source, entry.InstanceId); } private IList<EventLogEntry> _events; public IList<EventLogEntry> Events { get { if (_events == null) { _events = new List<EventLogEntry>(); for (int i = 0; i < _eventCollection.Count; i++) { EventLogEntry entry = _eventCollection[i]; _events.Add(entry); if (i % 1000 == 0) Console.Write("."); } } return _events; } } public int Count { get { return Events.Count; } } } }