c# – 如何使用文件夹读取事件日志?

我想以编程方式获取出现在eventvwr文件夹中的事件日志.这个适用于
Windows 8应用程序:Microsoft-Windows-AppHost / Admin.我是以管理员身份运行的.

这不起作用:

System.Diagnostics.EventLog.SourceExists("Microsoft-Windows-AppHost/Admin");

这也不起作用:

EventLogQuery queryMicrosoftWindowsAppHost = new EventLogQuery("Microsoft-Windows-AppHost/Admin", PathType.LogName);
_eventsMicrosoftWindowsAppHost = new List<EventRecordWrittenEventArgs>();
_eventLogWatcherMicrosoftWindowsAppHost = new EventLogWatcher(queryMicrosoftWindowsAppHost);
_eventLogWatcherMicrosoftWindowsAppHost.EventRecordWritten += (object sender, EventRecordWrittenEventArgs e) =>
{
    _eventsMicrosoftWindowsAppHost.Add(e);
};
_eventLogWatcherMicrosoftWindowsAppHost.Enabled = true;

最佳答案 您可以使用以下代码阅读事件日志:

EventLogReader reader = new EventLogReader("Microsoft-Windows-AppHost/Admin");
var evt = reader.ReadEvent();
while (evt!= null)
{
    // Write the message to the console
    Console.WriteLine(evt.FormatDescription());
    evt = reader.ReadEvent();
}

如果要附加处理程序,则代码很接近,但您只需将字符串传递给观察程序,而不是使用查询对象:

var watcher = new EventLogWatcher("Microsoft-Windows-AppHost/Admin");
watcher.EventRecordWritten += (object s, EventRecordWrittenEventArgs e1) =>
    {
        Console.WriteLine(e1.EventRecord.FormatDescription());
    };
watcher.Enabled = true;
点赞