Hey Folks. I have an app that writes to the windows event log. Now i want the same app to be able to read the event log an process the info that is in there.
I use my own dll to do my reading and writing. The Code for the Reading:
public static EventLog getEventLog(string Source, string Log)
{
using(EventLog ev = new EventLog(Log, System.Environment.MachineName, Source))
{
if (ev.Entries.Count <= 0)
{
return null;
}
else
{
return ev;
}
}
}
Here is the code i use to handle the eventlog
private void ProcessEvents()
{
using (EventLog ev = EventComms.EventComms.getEventLog("Application", "Application"))
{
for (int i = ev.Entries.Count - 1; i >= ev.Entries.Count; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
Console.WriteLine("Event ID : " + CurrentEntry.InstanceId);
开发者_如何学JAVA Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
Console.WriteLine("Message : " + CurrentEntry.Message + "\n");
}
}
}
Now when i try and do something with the returned Log i get an (ObjectDisposedException was unhandled Message=Cannot access a disposed object.)
exception.
I get the exception when i use ev.Entries.Count
Why do i get the error, and what is the best way to deal with it?
You are disposing the returned EventLog
object in the getEventLog
method. Remove the using
statement. Actually, the getEventLog
method can return null
which you don't check for later. I suggest dropping the method all together and using this code instead (where I also changed how you loop):
private void ProcessEvents()
{
using (EventLog ev = new EventLog("Application", System.Environment.MachineName, "Application"))
{
for (int i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
Console.WriteLine("Event ID : " + CurrentEntry.InstanceId);
Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
Console.WriteLine("Message : " + CurrentEntry.Message + "\n");
}
}
}
Your getEventLog
function is disposing the EventLog
object (the using
statement auto disposes it once it returns).
Try the following equivalent code:
private void ProcessEvents()
{
using (EventLog ev = new EventLog("Application", System.Environment.MachineName, "Application"))
{
if (ev.Entries.Count <= 0))
{
return;
}
for (int i = ev.Entries.Count - 1; i >= ev.Entries.Count; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
Console.WriteLine("Event ID : " + CurrentEntry.InstanceId);
Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
Console.WriteLine("Message : " + CurrentEntry.Message + "\n");
}
}
}
精彩评论