How to Get a Stack Trace from C# without throwing Exception
Monday 21 December 2009 @ 9:48 am

 

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() );
            }
        }
    }


}
Comments (2) - Posted in ASP.NET 2.0  




2 Responses to “How to Get a Stack Trace from C# without throwing Exception”

  1. Mats Says:

    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

  2. Rahul Says:

    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

Leave a Reply