Get call stack list in VB.net

By Allen Stoner

When logging events and problems it is often helpful to know what method the problem occured in. In .NET this is finally relatively easy to do with the use of the StackTrace, StackFrame and MethodBase objects. See the sample VB.NET for a procedure that returns a list of all the parent procedures. It displays: CheckOther<--Main Main in a console window.

Imports System.Reflection
Imports System.Diagnostics

Module Module1

    Sub Main()
        CheckOther()
       Console.WriteLine(GetSource)
       Console.ReadKey()
    End Sub

    Private Sub CheckOther()
       Console.WriteLine(GetSource)
    End Sub

    Private Function GetSource() As String
        Dim st As StackTrace = New StackTrace()
        Dim sf As StackFrame = st.GetFrame(1)

        Dim Source As String = ""
        For Each sf In st.GetFrames
           Source += sf.GetMethod.Name & "<--"
        Next
       Source = Source.Substring(0, (Source.LastIndexOf("<--")))  ' Take the delimiter off the end
       Source = Source.Substring(Source.IndexOf("<--") + 3)       ' Remove the lowest method as it's this routine
        GetSource = Source
    End Function

End Module

Get call stack list in VB.net  (1495 Views)