How to Get a Stack Trace from C# without throwing Exception

Posted by Peter Kellner on December 21, 2009 · 2 mins read

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


}