This tutorial introducesVB. NETHow to getCall the current processMethod Name and class name.
This article describes how VB. NET (VB 2008, VB 2005) obtains the names of the Calling methods and classes that call the current process.
Mainly usedSystem. Diagnostics. StackTraceAndSystem. Diagnostics. StackFrame, AndStackFrameMethod:GetFileName,GetFileLineNumber,GetMethod. Name,GetMethod. ReflectedType. Name.
Sample Code
As shown in the following sample code, we have two classes: Class1 and Class2. Class1 has a method called LoadXmlFile to call the WriteToFile method of Class2.
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
In Class2, we wrote some code to get the name of the Class1 that calls it, the file path, the name of the calling method, and the number of lines that execute the call in the calling file.
Key Points
1. Imports System. Diagnostics.
2. StackTrace (System. Diagnostics. StackTrace) and StackFrame (System. Diagnostics. StackFrame) are used ).
3. StackTrace. GetFrame (1) is used ).
4. StackFrame. GetMethod. Name to obtain the method (calling method name) for calling the current process ).
5. StackFrame. GetMethod. ReflectedType. Name to get the name of the class calling the current process (calling class Name ).
6. StackFrame. GetFileLineNumber. ToString to get the number of lines of statements calling the current process in the file.
7. StackFrame. GetFileName to obtain the file path of the current call process.