利用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 == )
{
int x = Convert.ToInt32(args[]);
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, );
DateTime dateTo = dateFrom.AddMonths(); 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 > )
{
Console.WriteLine();
Console.WriteLine(GetLogEntryText(list[]));
if (list.Count > )
{
int l = list.Count - ;
Console.WriteLine(GetLogEntryText(list[l]));
}
} dt = dt.AddDays();
}
} 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 = ; i < _eventCollection.Count; i++)
{
EventLogEntry entry = _eventCollection[i];
_events.Add(entry);
if (i % == ) Console.Write(".");
}
} return _events;
}
} public int Count
{
get { return Events.Count; }
} }
}