I was wondering how I could reach event Log entries. I have a client server application and it executes without problems. What i am looking for is all instances of log with the id of 1149. This log is of the remote connection entries. I have taken a piece of code, here it is.
string logType = "System";
string str = "";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int LastLogToShow = ev.Entries.Count;
if (LastLogToShow <= 0)
Console.WriteLine("No Event Logs in the Log :" + logType);
// Read the last 2 records in the specified log.
int i;
for (i = ev.Entries.Count; i >= LastLogToShow - 1000 ; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.InstanceId == 1149)
{
str += "Event type: " + CurrentEntry.EntryType.ToString() + "\n" +
"Event Message: " + CurrentEntry.Message + CurrentEntry + "\n" +
"Event Time: " + CurrentEntry.TimeGenerated.ToShortTimeString() + "\n" +
"Event : " + CurrentEntry.UserName +"\n" +"\n";
}
}
ev.Close();
return str;
The thing is I get the 42567 index is out of bounds exception everytime. I also dont know if it will work after that, so questions may follow.
EDIT: Indeed, the problem was me reaching out of the eventlog with my index like you guys said. Using this line for the loop solved my problem here and I am able to reach the eventlog now, if anyone is looking around, this solution worked for me, so thank you all so much.
for (i = ev.Entries.Count - 1; i >= 0; i--)
This for (i = ev.Entries.Count; i >= LastLogToShow - 1000 ; i--)
is causing your error. I don't really get what you're trying to do here. For one if you have less than 1000 entries, your i
can be negative. When you use a negative value as the index of an array you will get "index is out of bounds exception". When you are trying to process only the last 2 records (as your commentary above the for-loop suggests) you should just use this:
for (i = ev.Entries.Count - 1; i >= ev.Entries.Count - 2; i--)
Of course you will still have to check if there is more than 2 entries because if there are 0 entries, the code will still go into the for-loop and try to access the array with negative indexes:
if(ev.Entries.Count < 2)
return str;
for (i = ev.Entries.Count - 1; i >= ev.Entries.Count - 2; i--)
Edit: Also just noticed even if there are more than 1000 records, when you go into the for-loop for the first time you will have ev.Entries[ev.Entries.Count]
. Since array-indexes are zero-based you have to substract 1 from the count to get the last element of an array.