NullReferenceException при чтении описания журнала событий с использованием класса System.Management - PullRequest
0 голосов
/ 25 января 2011

Я могу запросить / прочитать журнал событий, используя 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

Редактировать: Это происходит только для каждого элемента «Сообщение» в цикле, пока он получает другойПредметы.Кроме того, действительно, в 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()

1 Ответ

0 голосов
/ 07 февраля 2011

На основании предыдущего использования (я делал то же самое в C #) Сообщение может быть нулевым, вам нужно проверить это.

...