As I was implementing some logging into an application, I was thinking that it would be nice to include the stacktrace in the log information. I know that you can easily get this information in case of an error, but I did not know if you could do the same thing when you just want to log something without any error.
As I found out this is possible thanks to the StackTrace class. You can get the frames using StackTrace.GetFrames method.
1: using System.Diagnostics;
2:
3: [STAThread]
4: public static void Main()
5: {
6: StackTrace stackTrace = new StackTrace(); // get call stack
7: StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
8:
9: // write call stack method names
10: foreach (StackFrame stackFrame in stackFrames)
11: {
12: Console.WriteLine(stackFrame.GetMethod().Name); // write method name
13: }
14: }