views:

81

answers:

3

I was wondering if it's possible to convert the string StackTrace in the exception to a more structured data object?

Or is there a method that can get me this information while I am catching the exception? Maybe something using reflection?

Thanks!

+3  A: 

Check out the System.Diagnostics.StackTrace class. You can create the object and walk over the frames.

StackTrace st = new StackTrace();
foreach (var frame in st.GetFrames())
{
    Console.WriteLine(frame.GetFileName().ToString()
        + ":"
        + frame.GetFileLineNumber().ToString());
}
Brian Ensink
This is a really handy class. If you ever want to determine what method called you, and if there are any custom attributes defined on that method then you need this class.
Josh
well i found out that u can pass an exception object to the contructor of StackTrace(). so bassicaly that is it :)
Karim
@Karim: that is the easier way :)
leppie
the problem is that i am sending this Exception object to a function that is handling the logging of the exception. so if i create a StackTrace() , it will give me the current stack trace and not the one associated with the exception
Karim
are you sure you are creating it from the exception? that seems to work for me.
Matt Breckon
+1  A: 

Essentially, if you want a consistent solution you are out of luck.

You can get a hodge podge solution by storing the stack trace on exception construction.

But, there are no hooks in the framework that are called when an exception is thrown.

Sam Saffron
+2  A: 

Use StackTrace class with constructor accepting Exception:

static void ShowExceptionStackTrace(Exception ex)
{
    var stackTrace = new StackTrace(ex, true);

    foreach (var frame in stackTrace.GetFrames())
        Console.WriteLine(frame.GetMethod().Name);
}
Konstantin Spirin