This tutorial describes how vb.net Gets the method name and class name for invoking the current procedure .
This article describes how VB.net (VB 2008, VB 2005) Gets the names of the method names (calling methods) and classes (calling Class) that invoke the current procedure.
The main use of System.Diagnostics.StackTrace and System.Diagnostics.StackFrame, as well as the stackframe method: getfilename,getfilelinenumber,getmethod.name, GetMethod.ReflectedType.Name .
Sample code
As shown in the following example code, we have two classes: Class1 and Class2, and Class1 has a method called Loadxmlfile Class2 method that invokes WriteToFile.
Imports system.xmlpublic Class Class1 public Sub loadxmlfile () Dim filePath as String = "C:a.xml" Dim Xdoc as New xml.xmldocument Try
Xdoc. Load (FilePath)
Catch ex as Exception
Dim log as New Class2
Log. WriteToFile ("Error.") Load XML File failed ")
End Try-end SubEnd Class
Imports system.diagnosticspublic Class Class2 public Sub writetofile (ByVal Log As String) Dim clsname As String = ""Dim mtdname as String = ""
Dim Lnno as String = ""
Dim Codefilepath As String = "Dim st As New StackTrace (True)
If St. Framecount > 1 Then
Dim SF as StackFrame = St. GetFrame (1)
Mtdname = SF. Getmethod.name
Debug.WriteLine (mtdname) clsname = SF. GetMethod.ReflectedType.Name
Debug.WriteLine (clsname) Lnno = SF. Getfilelinenumber.tostring
Debug.WriteLine (lnno) Codefilepath = SF. GetFileName
Debug.WriteLine (Codefilepath)
End If End SubEnd Class
Inside Class2, we wrote some code to get the name of the Class1 that called it, the path to the file, the name of the calling method, and the number of rows in the call file that were executing the call.
Points
1. To Imports System.Diagnostics.
2. StackTrace (System.Diagnostics.StackTrace) and StackFrame (System.Diagnostics.StackFrame) are to be used.
3. To use Stacktrace.getframe (1).
4. StackFrame.GetMethod.Name gets the method that invokes the current procedure (calling).
5. StackFrame.GetMethod.ReflectedType.Name gets the name of the class that invoked the current procedure (calling class name).
6. StackFrame.GetFileLineNumber.ToString gets the number of lines in the file where the statement calling the current procedure is invoked.
7. Stackframe.getfilename gets the path to the file where the current procedure is invoked.