以编程方式从事件日志中读取

时间:2010-12-15 09:35:01

标签: .net c#-3.0 event-log

嘿伙计们。 我有一个写入Windows事件日志的应用程序。 现在我希望相同的应用程序能够在事件日志中读取该过程中的信息。

我用自己的dll来做我的阅读和写作。阅读准则:

    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; 

            }            
        }
    }

以下是我用来处理事件日志的代码

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);
                Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
                Console.WriteLine("Message :  " + CurrentEntry.Message + "\n");
            }   
        }                
    }

现在,当我尝试使用返回的Log执行某些操作时,我会收到(ObjectDisposedException was unhandled Message=Cannot access a disposed object.)个异常。 当我使用ev.Entries.Count

时,我得到了例外

为什么我会收到错误,处理错误的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

您正在EventLog方法中处理返回的getEventLog对象。删除using语句。实际上,getEventLog方法可以返回null,您不会在以后查看。我建议将所有方法放在一起并使用此代码(我也改变了循环方式):

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");
    }
  }
}

答案 1 :(得分:0)

getEventLog函数处理 EventLog对象(using语句一旦返回就会自动处理它。)

尝试以下等效代码:

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");
        }   
    }                
}