December 21st, 2009How to Get a Stack Trace from C# without throwing Exception
Say you have some logging in your code that finds something unusual going on. In my case, I have a DataContext that I check to make sure it’s not already open before I open it. The method that I call the DataContext in is a utility method that is buried many layers down. When this problem is found, I don’t want to throw an exception, but I do want to log where I was. It does not help me to know that I’m in my utility method. I need to know the stack.
Below is some simple code that lets me do this. Notice, it’s important to call StackTrace with true, otherwise the line numbers don’t appear.
HTH’s!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { TestClass.GoNow(); } } class TestClass { public static void GoNow() { var stackTrace = new StackTrace(true); foreach (var r in stackTrace.GetFrames()) { Console.WriteLine("Filename: {0} Method: {1} Line: {2} Column: {3} ", r.GetFileName(),r.GetMethod(), r.GetFileLineNumber(), r.GetFileColumnNumber() ); } } } }









December 21st, 2009 at 10:37 am
this might interestd you, coming in VS2010
http://blogs.msdn.com/ianhu/archive/2009/05/13/historical-debugging-in-visual-studio-team-system-2010.aspx
December 23rd, 2009 at 5:59 am
First of all. Thanks very much for your useful post.
I just came across your blog and wanted to drop you a note telling you how impressed I was with the
information you have posted here.
Please let me introduce you some info related to this post and I hope that it is useful for community.
There is a good C# resource site, Have alook
http://CSharpTalk.com
Thanks again
Rahul
August 6th, 2011 at 10:33 pm
Hello, i think that i saw you visited my website so i came to “return the favor”.I’m attempting to find things to improve my web site!I suppose its ok to use some of your ideas!!
October 26th, 2011 at 12:53 am
Nice work but its probably easier to use Environment.StackTrace
January 3rd, 2012 at 6:33 am
Just for info, this might break when you run de-attached from a debugger in Release mode as the StackTrace changes.
January 5th, 2012 at 12:11 am
How could We have missed this blogging site! You’ll find it amazing. Your structure is flawless, like you realize just how to proceed to accomplish make folks flock on your web page! I also much like the point of view you introduced to this matter. It really is like you’ve an insight that almost all individuals have not viewed previously. So remarkable to learn a web site similar to this.