使用C#throw读取事件日志文件(.evt)数据无效

时间:2016-05-26 15:29:30

标签: c# event-log

我尝试从C#中读取事件日志文件 .evt 文件,并使用过滤器仅获取 Framework 2.0 条目:

string query = "*[System/Provider/@Name=\"ASP.NET 2.0.50727.0\"]"; 

var elQuery = new EventLogQuery("C:\evento.evt", PathType.FilePath, query);
var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery);

List<EventRecord> eventList = new List<EventRecord>();

for (EventRecord eventInstance = elReader.ReadEvent(); null != eventInstance; eventInstance = elReader.ReadEvent())
{
    string source = eventInstance.ProviderName;

    eventList.Add(eventInstance);
    if (eventInstance.Properties.Count > 3)
    {
        string dateTime = eventInstance.Properties[2].Value.ToString(); 
        string message = eventInstance.Properties[1].Value.ToString();
    }
}

如果我设置断点,我会看到一些事件日志条目的正确结果,但是如果我按F5, elReader.ReadEvent()会抛出错误数据无效< /强>

任何帮助?谢谢!

2 个答案:

答案 0 :(得分:1)

for循环中,直到迭代后才会检查条件。 在这里,elReader.ReadEvent()将返回null,并在eventInstance中设置该eventInstance。然后循环体将运行,然后它将检查null是否为while并停止。

执行此类读取直到空循环的常规方法是使用while ((EventRecord eventInstance = elReader.ReadEvent()) != null) { // as before } 循环,在此设置变量并同时检查条件:

eventInstance

这将像以前一样从ReadEvent()设置null,但检查在运行循环体之前是否返回git log --all filePath

在.NET中使用此模式的经典其他地方是在文本文件中读取行,例如请参阅此example on MSDN

答案 1 :(得分:0)

public static void LeerPrint() {

        string logType = "Microsoft-Windows-PrintService/Operational";
        string query = "*[System/EventID=307]";

        var elQuery = new
            EventLogQuery(logType, PathType.LogName, query);
        var elReader = new EventLogReader(elQuery);

        for (EventRecord eventInstance = elReader.ReadEvent(); eventInstance != null; eventInstance = elReader.ReadEvent())
        {
            string source = eventInstance.ProviderName;
            Class1.WriteLog("1:"+eventInstance.Properties[1].Value.ToString() , config.validadirectorio());
            Class1.WriteLog("2:" + eventInstance.Properties[2].Value.ToString(), config.validadirectorio());
            Class1.WriteLog("3:" + eventInstance.Properties[3].Value.ToString(), config.validadirectorio());
            Class1.WriteLog("4:" + eventInstance.Properties[4].Value.ToString(), config.validadirectorio());
            Class1.WriteLog("5:" + eventInstance.Properties[5].Value.ToString(), config.validadirectorio());
            Class1.WriteLog("6:" + eventInstance.Properties[6].Value.ToString(), config.validadirectorio());
            Class1.WriteLog("7:" + eventInstance.Properties[7].Value.ToString(), config.validadirectorio());

            
        }


    }