Skip to content

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

Updated: at 02:12 PM

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

<span class="kwrd">class</span> TestClass
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> GoNow()
    {
        var stackTrace = <span class="kwrd">new</span> StackTrace(<span class="kwrd">true</span>);
        <span class="kwrd">foreach</span> (var r <span class="kwrd">in</span> stackTrace.GetFrames())
        {
            Console.WriteLine(<span class="str">&quot;Filename: {0} Method: {1} Line: {2} Column: {3}  &quot;</span>,
                r.GetFileName(),r.GetMethod(), r.GetFileLineNumber(),
                r.GetFileColumnNumber() );
        }
    }
}

}

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects