Read from windows event log


In this article , author explain about Read from windows event log with example code snippet

This VB.NET example shows how to read from WIndows Event Log

								
Imports Microsoft.VisualBasic.FileIO
Public Shared sbMessage As New System.Text.StringBuilder

#Region "Read NT Event Log"
Private Sub btnReadNTEventLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadNTEventLog.Click
Try
Dim arrMessage As New ArrayList
Dim intarrMessageCount As Integer
Dim LogName As String = "Application" .Reads from Event log named Application

If Val(txtNoOfRecords.Text) < 0 Then
MsgBox("No: Of Records should be greater than 0")
Exit Sub
End If

arrMessage = GetFromLogEntry(LogName, Val(txtNoOfRecords.Text))
If arrMessage.Count > 0 Then
If arrMessage.Count = 1 Then
If InStr(arrMessage(0), "No Eventlogs") Then
MessageBox.Show(arrMessage(0).ToString, "No LogFile", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)
Exit Sub
End If
End If
For intarrMessageCount = 0 To arrMessage.Count - 1
sbMessage.Append(vbCrLf & arrMessage(intarrMessageCount) & vbCrLf)
Next
Dim f As New frmShowErrorMessage
f.ShowDialog()
sbMessage.Remove(0, sbMessage.Length - 1)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub


Private Function GetFromLogEntry(ByVal LogName As String, Optional ByVal RecCnt As Integer = -1) As ArrayList
Try

Dim objLogs() As EventLog
Dim arrMessage As New ArrayList
Dim intLogCount As Integer
Dim objLog As EventLog
Dim boolLogExists As Boolean = 0 'Checks whether logfile exists

objLogs = EventLog.GetEventLogs(".")

For Each objLog In objLogs
If objLog.LogDisplayName = LogName Then
boolLogExists = True
Exit For
End If
Next

If boolLogExists = True Then
'If user entered some value in No:of records, this loop will execute
If RecCnt > 0 Then
If RecCnt > objLog.Entries.Count Then
arrMessage.Add("Total No: Of records in Eventlog is only " & objLog.Entries.Count)
Return arrMessage
Exit Function
End If
For intLogCount = 0 To RecCnt - 1
arrMessage.Add(objLog.Entries(objLog.Entries.Count - intLogCount - 1).Message & vbCrLf & objLog.Entries(objLog.Entries.Count - intLogCount - 1).TimeWritten)
Next
Else
For intLogCount = 0 To objLog.Entries.Count - 1
arrMessage.Add(objLog.Entries(objLog.Entries.Count - intLogCount - 1).Message & vbCrLf & objLog.Entries(objLog.Entries.Count - intLogCount - 1).TimeWritten)
Next
End If
Else
arrMessage.Add("No Eventlogs Present with Name:" & LogName)
End If

Return arrMessage
Catch ex As Exception
Throw ex
End Try
End Function
#End Region



Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: