using System; using System.Diagnostics; class MyClass { [STAThread] static void Main(string[] args) { MyClass mc = new MyClass(); try { mc.MyPublicMethod(); } catch (Exception) { // Create a StackTrace that captures // filename, line number and column // information, for the current thread. StackTrace st = new StackTrace(true); for(int i =0; i< st.FrameCount; i++ ) { // High up the call stack, there is only one stack frame StackFrame sf = st.GetFrame(i); Console.WriteLine("\nHigh Up the Call Stack, Method: {0}", sf.GetMethod() ); Console.WriteLine( "High Up the Call Stack, Line Number: {0}", sf.GetFileLineNumber()); } } } public void MyPublicMethod () { MyProtectedMethod(); } protected void MyProtectedMethod () { MyInternalClass mic = new MyInternalClass(); mic.ThrowsException(); } class MyInternalClass { public void ThrowsException() { try { throw new Exception("A problem was encountered."); } catch (Exception e) { // Create a StackTrace that captures filename, // line number and column information. StackTrace st = new StackTrace(true); string stackIndent = ""; for(int i =0; i< st.FrameCount; i++ ) { // Low down the call stack there are four // stack frames, one for each method invocation. StackFrame sf = st.GetFrame(i); Console.WriteLine("\n" + stackIndent + " Method: {0}", sf.GetMethod() ); Console.WriteLine( stackIndent + " File: {0}", sf.GetFileName()); Console.WriteLine( stackIndent + " Line Number: {0}", sf.GetFileLineNumber()); stackIndent += " "; } throw e; } } } }The following is the output from the example.
C:\StackTraceSample\bin\Debug>StackTraceSample Method: Void ThrowsException() File: c:\pp\samples\stacktraceframe\myclass.cs Line Number: 50 Method: Void MyProtectedMethod() File: c:\pp\samples\stacktraceframe\myclass.cs Line Number: 37 Method: Void MyPublicMethod() File: c:\pp\samples\stacktraceframe\myclass.cs Line Number: 31 Method: Void Main(System.String[]) File: c:\pp\samples\stacktraceframe\myclass.cs Line Number: 12 High Up the Call Stack Method: Void Main(System.String[]) High Up the Call Stack Line Number: 17There appears to be a little gotcha with getting the call stack and it has to do with compiler optimisations. The following is taken from the MSDN documentation.
StackTrace might not report as many method calls as expected, due to code transformations that occur during optimization.Regards