使用 System.Management 类读取事件日志的描述时出现 NullReferenceException

发布于 2024-10-14 05:54:55 字数 5119 浏览 6 评论 0原文

我可以使用 VB.NET 2005 (Win XP) 查询/读取事件日志。但我在读取事件日志的“消息”/“描述”时仍然遇到问题。

我在阅读事件日志的“消息”/“描述”时收到 System.NullReferenceException。

另外,当我使用 System.Diagnostics.EventLog 并通过一个读取所有事件时,我能够读取事件的消息/描述。

这是代码:

Public Sub ReadEvent()
    Dim iCount As Int16
    Dim PastFourHours As Date = Date.Now.AddHours(-4)
    Dim sQuery As String = "Select * from Win32_NTLogEvent Where Logfile = 'MyLogFile' AND TimeGenerated > '" & PastFourHours.ToString() & "'"

    Dim myConnectionOptions As New System.Management.ConnectionOptions
    Dim myManagementScope As System.Management.ManagementScope
    Dim myObjectSearcher As System.Management.ManagementObjectSearcher
    Dim colLoggedEvents As System.Management.ManagementObjectCollection
    Dim objEvent As System.Management.ManagementObject

    With myConnectionOptions
        .Impersonation = System.Management.ImpersonationLevel.Impersonate
        .Authentication = System.Management.AuthenticationLevel.Packet
    End With

    myManagementScope = New System.Management.ManagementScope("\\.\root\cimv2", myConnectionOptions)
    myManagementScope.Connect()                         'connect to WMI namespace

    If (Not myManagementScope.IsConnected) Then
        Call PrintLogToAFile("Could not connect to WMI namespace")
    End If

    myObjectSearcher = New System.Management.ManagementObjectSearcher(myManagementScope.Path.ToString, sQuery.ToString())
    colLoggedEvents = myObjectSearcher.Get()               'execute query

    For Each objEvent In colLoggedEvents
        Call PrintLogToAFile("Category: " + objEvent("Category").ToString())                           
        Call PrintLogToAFile("Message: " + objEvent("Message").ToString())
        Call PrintLogToAFile("Type: " + objEvent("Type").ToString())                                   

        iCount = iCount + 1
    Next

    Call PrintLogToAFile("Number of records: " + iCount.ToString())
End Sub

编辑:它仅在循环中获取其他项目时发生在“Message”的每个项目上。此外,根据下面给出的事件日志结构,在 objEvent 中确实有一个键为“Message”的元素,

//Event Log structure:
uint16 Category;
string CategoryString;
string ComputerName;
uint8 Data[];
uint16 EventCode;
uint32 EventIdentifier;
uint8 EventType;
string InsertionStrings[];
string Logfile;
string Message;
uint32 RecordNumber;
string SourceName;
datetime TimeGenerated;
datetime TimeWritten;
string Type;
string User;

这是完整的堆栈跟踪:

System.NullReferenceException was unhandled
  Message="Object reference not set to an instance of an object."
  Source="WindowsApplication1"
  StackTrace:
       at WindowsApplication1.GlobalMod.ReadEvent() in G:\WindowsApplication1\GlobalMod.vb:line 88
       at WindowsApplication1.Form1.BtnRead_Click(Object sender, EventArgs e) in G:\WindowsApplication1\Form1.vb:line 11
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

I am able to query/read the event log using VB.NET 2005 (Win XP). But still I have a problem reading the "Message" / "description" of the event log.

I am getting a System.NullReferenceException while reading the "Message" / "Description" of the event log.

Also when I use System.Diagnostics.EventLog and read all the Event on by one I am able to read the message/description of the event.

This is the code:

Public Sub ReadEvent()
    Dim iCount As Int16
    Dim PastFourHours As Date = Date.Now.AddHours(-4)
    Dim sQuery As String = "Select * from Win32_NTLogEvent Where Logfile = 'MyLogFile' AND TimeGenerated > '" & PastFourHours.ToString() & "'"

    Dim myConnectionOptions As New System.Management.ConnectionOptions
    Dim myManagementScope As System.Management.ManagementScope
    Dim myObjectSearcher As System.Management.ManagementObjectSearcher
    Dim colLoggedEvents As System.Management.ManagementObjectCollection
    Dim objEvent As System.Management.ManagementObject

    With myConnectionOptions
        .Impersonation = System.Management.ImpersonationLevel.Impersonate
        .Authentication = System.Management.AuthenticationLevel.Packet
    End With

    myManagementScope = New System.Management.ManagementScope("\\.\root\cimv2", myConnectionOptions)
    myManagementScope.Connect()                         'connect to WMI namespace

    If (Not myManagementScope.IsConnected) Then
        Call PrintLogToAFile("Could not connect to WMI namespace")
    End If

    myObjectSearcher = New System.Management.ManagementObjectSearcher(myManagementScope.Path.ToString, sQuery.ToString())
    colLoggedEvents = myObjectSearcher.Get()               'execute query

    For Each objEvent In colLoggedEvents
        Call PrintLogToAFile("Category: " + objEvent("Category").ToString())                           
        Call PrintLogToAFile("Message: " + objEvent("Message").ToString())
        Call PrintLogToAFile("Type: " + objEvent("Type").ToString())                                   

        iCount = iCount + 1
    Next

    Call PrintLogToAFile("Number of records: " + iCount.ToString())
End Sub

Edit: It only occurs on each item of "Message" in the loop while it is getting the other items. Also indeed there is an element keyed as "Message" in the objEvent as per the event log structure given under

//Event Log structure:
uint16 Category;
string CategoryString;
string ComputerName;
uint8 Data[];
uint16 EventCode;
uint32 EventIdentifier;
uint8 EventType;
string InsertionStrings[];
string Logfile;
string Message;
uint32 RecordNumber;
string SourceName;
datetime TimeGenerated;
datetime TimeWritten;
string Type;
string User;

This is the full stack trace:

System.NullReferenceException was unhandled
  Message="Object reference not set to an instance of an object."
  Source="WindowsApplication1"
  StackTrace:
       at WindowsApplication1.GlobalMod.ReadEvent() in G:\WindowsApplication1\GlobalMod.vb:line 88
       at WindowsApplication1.Form1.BtnRead_Click(Object sender, EventArgs e) in G:\WindowsApplication1\Form1.vb:line 11
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拔了角的鹿 2024-10-21 05:54:55

根据以前的用法(我在 C# 中做了同样的事情)消息可以为空,您需要对此进行测试。

Based on previous usage (I was doing the same thing in C#) Message can be null, you need to test for that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文