日志程序编程问题
我用vs2010编写编写了如下读入日志内容的程序,但程序总是没有读取日志当中的内容,这么为什么?(注意:我是Win32程序练习该示例的)
using System;
using System.Diagnostics;
class MySample
{
public static void Main()
{
EventLog myNewLog = new EventLog();
myNewLog.Log = "MFCLog"; //MFCLog已经是事件查看器中注册的日志了,它关联的事件源是MFCProgramDesign
foreach(EventLogEntry entry in myNewLog.Entries)
{
Console.WriteLine("\tEntry: " + entry.Message); //打印日志的消息
}
}
}
疑问:
1、foreach循环体一直都没有被执行,为什么?
2、MFCLog日志已经在事件查看器中注册了,为什么程序读不了日志的内容。后来我查看myNewLog.Entries的Count成员值,发现总是为0,于是我猜想是不是如下两条语句存在问题
EventLog myNewLog = new EventLog();
myNewLog.Log = "MFCLog";
第一条语句创建一个新的实例
第二条语句为该实例指定一个日志名,但不包括日志内容
foreach循环语句就是对新实例进行遍历,而新实例没有内容,所有foreach循环体没有被执行。
如果是我猜想的那样,而这段程序是我从微软的MSDN上copy下来的,应该不会有问题啦,问题究竟出在什么地方呢,我该怎么解决才能读取到已经注册的日志(即:MFCLog)的内容呢,希望给出详细的程序代码啦,谢啦
[解决办法]
对照帮助中的示例
using System;using System.Diagnostics;using System.Threading;class MySample{ public static void Main(){ // Create the source, if it does not already exist. if(!EventLog.SourceExists("MySource")) { //An event log source should not be created and immediately used. //There is a latency time to enable the source, it should be created //prior to executing the application that uses the source. //Execute this sample a second time to use the new source. EventLog.CreateEventSource("MySource", "MyNewLog"); Console.WriteLine("CreatedEventSource"); Console.WriteLine("Exiting, execute the application a second time to use the source."); // The source is created. Exit the application to allow it to be registered. return; } // Create an EventLog instance and assign its source. EventLog myLog = new EventLog(); myLog.Source = "MySource"; // Write an informational entry to the event log. myLog.WriteEntry("Writing to event log."); }}