Here i am calculating the server re开发者_开发问答start count.
i need the server restart count for last 24 hours.
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();
and i have tried like
DateTime dt = DateTime.Now;
TimeSpan ts = dt.Subtract(CurrentEntry.TimeGenerated);
int hours = (ts.Days * 24) + ts.Hours;
Any suggestion?
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();
Edit:
Considering jCoder's comment about the enteries being sorted on TimeGenerated. Using this code will gain performance:
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++;
}
Use CurrentEntry.TimeGenerated
to check when it has happened.
put one more condition at if (CurrentEntry.Source.ToUpper() == "USER32")
to check if TimeGenerated is in last 24 hours
This code will give you the count of events, in tha last day, that have a source of USER32
in the System event log.
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();
}
EDIT: Or Even better, taking good bits from Mangus's answer
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
)
}
If "USER32" events do not have a direct correllation with system restart events, this will not give you a count of system restarts.
精彩评论