C#获取操作系统日志信息

C#获取操作系统日志信息
C#获取操作系统日志信息

C#获取操作系统日志信息

利用C#编程,查看系统日志,介绍两个日志类:EventLog和EventLogEntry类,以及与系统日志进行交互。

.NET框架类库提供了EventLog类和EventLogEntry类与系统日志进行交互.二者属于System.Diagnostics命名空间.

首先声明一变量:private EventLogEntryCollection eventCollection 代表系统日志的集合.

EventLog类的属性主要有:

Entris返回一个EventLogEntryCollection型值,代表事件日志的内容.

og 获取或者返回日志的名称,其中应用程序日志是Application,系统日志是System,安全日志是Security,默认值为空字符串.

LogDisplayName 获取事件日志的友好名称

MachineName 获取或设置在其上读取或写入事件的计算机名称

Source 获取或设置在写入事件日志时要注册和使用的源名称

EventEntryCollection类定义EventLogEntry实例集合的大小和枚举数.

EventLogEntry类的一些主要属性如下:

Category 获取与该项的CategoryNumber对应的文本

CategoryNumber 获取该项的类别号

Data 获取与该项对应的二进制数据

EntryType 获取该项的事件类型,其值属于EventLogEntryType枚举,这个枚举的主要成员如下:

Error 错误事件,它指示用户应该知道的严重问题,比如功能或数据丢失

FailureAudit 失败审核事件.它指示当审核访问尝试失败,比如打开文件的尝试失败时发生的安全事件

Information 信息事件.它指示重要,成功的事件

SuccessAudit 成功审核事件.它指示当审核访问尝试成功,比如成功登录时发生的安全事件

Warning 警告事件.它指示并不立即具有重要性的问题,但此问题可能表示将来会导致问题的条件.

EventID 获取此事件项的应用程序特定事件标识符

Index 获取该项在事件日志中的索引

MachineName 获取在产生该项的计算机的名称

Message 获取与该事件的本地化消息

ReplacementStrings 获取对应该项替换字符串

Source 获取生成该事件的应用程序的名称

TimeGenerated 获取生成该事件的本地时间

TimeWritten 获取在日志写入该事件的本地时间

UserName 获取负责该事件的用户的名称

示例代码如下:

usingSystem.Diagnostics;

usingSystem;

namespaceLogView

{

publicclassSysLogView

{

privateEventLogEntryCollectioneventCollection; privateEventLogsystemEvent;

publicSysLogView()

{

systemEvent=newEventLog();

systemEvent.Log="System";

eventCollection=systemEvent.Entries;

}

privatevoidLoadEventLog(intc)

{

EventLogsystemEvent=newEventLog();

systemEvent.Log="System";

eventCollection=systemEvent.Entries;

intlength=eventCollection.Count;

EventLogEntryentry=eventCollection[c];

string[]title={

entry.EntryType.ToString(),

entry.TimeGenerated.ToLongDateString(),

entry.TimeGenerated.ToLongTimeString(),

entry.Source,

entry.Category,

entry.EventID.ToString(),

https://www.360docs.net/doc/bf13920876.html,erName,

entry.MachineName

};

for(intj=0;j

{

Console.WriteLine(title[j]);

}

Console.WriteLine("n"+eventCollection[c].Message); }

privatestringDisplayEventCount()

{

return(eventCollection.Count.ToString());

}

publicstaticvoidMain(string[]args)

{

SysLogViewslv=newSysLogView();

if(args.Length==1)

{

intx=Convert.ToInt32(args[0]);

slv.LoadEventLog(x);

}

else

{

Console.WriteLine("Eventcount:"+slv.DisplayEventCount());

Console.WriteLine("QueryMessage:SysLogView.exeNumber"); }

}

}

}

相关主题
相关文档
最新文档