There are times when you will need to write something to the screen to debug your VB.NET code and find it impossible as there are certain things that doesn’t really display a page. A web service don’t normally show a web page after it’s been called and it’s such a pain to debug errors if you can’t really see what’s going wrong. Here’s a handy way to debug your code, write your error to an error log where you can view the log easily. Here are some code examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | Imports System Imports System.IO Imports System.Data Private filePath As String Private fileStream As FileStream Private streamWriter As StreamWriter Public Sub OpenFile() Dim strPath As String strPath = MapPath("~") & "\Error.log" If System.IO.File.Exists(strPath) Then fileStream = New FileStream(strPath, FileMode.Append, FileAccess.Write) Else fileStream = New FileStream(strPath, FileMode.Create, FileAccess.Write) End If StreamWriter = New StreamWriter(fileStream) End Sub Public Sub WriteLog(ByVal strComments As String) OpenFile() StreamWriter.WriteLine(strComments) CloseFile() End Sub Public Sub CloseFile() StreamWriter.Close() fileStream.Close() End Sub |
Here’s how you would use the error log
1 2 3 4 5 6 | Try 'Do something Catch ex As Exception WriteLog("Error :" & Date.Today.ToString & " " & ex.Message) End Try |
