这里我正在计算服务器重启次数。
我需要过去24小时的服务器重启计数。
string logType = "System";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int count=0;
for (int i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.Source.ToUpper() == "USER32")
{
count = count + 1;
}
}
ev.Close();
我试过像
DateTime dt = DateTime.Now;
TimeSpan ts = dt.Subtract(CurrentEntry.TimeGenerated);
int hours = (ts.Days * 24) + ts.Hours;
有什么建议吗?
答案 0 :(得分:3)
var ev = new EventLog("system", System.Environment.MachineName);
var count = ev.Entries.Cast<EventLogEntry>()
.Where (e => e.TimeGenerated >= DateTime.Now.AddDays(-1)
&& e.Source.Equals("USER32", StringComparison.CurrentCultureIgnoreCase)).Count();
修改强>
考虑jCoders评论在TimeGenerated上排序的条目。使用此代码将获得性能:
var ev = new EventLog("system", System.Environment.MachineName);
int count = 0;
var y = DateTime.Now.AddDays(-1);
for (int i = ev.Entries.Count - 1; i >= 0 ; i--)
{
if(ev.Entries[i].TimeGenerated < y)
break;
if(ev.Entries[i].Source.Equals("USER32", StringComparison.CurrentCultureIgnoreCase))
count++;
}
答案 1 :(得分:1)
使用CurrentEntry.TimeGenerated
检查发生的时间。
在if (CurrentEntry.Source.ToUpper() == "USER32")
再添加一个条件来检查TimeGenerated是否在过去24小时内
答案 2 :(得分:1)
此代码将为您提供最后一天在系统事件日志中有USER32
来源的事件计数。
int count; //your result
//When yesterday became today
DateTime yesterday = DateTime.Now.Subtract(new TimeSpan(24, 0, 0));
using (EventLog appLog = new EventLog("System"))
{
count = appLog.Entries.OfType<EventLogEntry>().Where(
e => (e.Source.ToUpperInvariant == "USER32") &&
(e.TimeGenerated > yesterday)).Count();
}
编辑:或者甚至更好,从Mangus的答案中取得好处
DateTime yesterday = DateTime.Now.AddDays(-1);
int count = 0;
using (Eventlog appLog = new EventLog("System"))
{
count = appLog.Entries.OfType<EventLogEntry>().Count(
e.Source.Equals("USER32", StringComparison.CurrentCultureIgnoreCase) &&
e.TimeGenerated > yesterday
)
}
如果“USER32”事件与系统重启事件没有直接关联,则不会计算系统重启次数。