views:

336

answers:

2

Okay; assuming this code running in debug mode -

static StackFrame GetTopFrameWithLineNumber(Exception e)
{
    StackTrace trace = new StackTrace(e);
    foreach (StackFrame frame in trace.GetFrames())
    {
        if (frame.GetFileLineNumber() != 0)
        {
            return frame;
        }
    }
    return null;
}

I'm ALWAYS returning null. Why do the stack frames have no line numbers when if I inspect the Exception.StackTrace string, it clearly does have them for any non-framework code? Is there some issue with constructing a stack trace from an exception that i'm not aware of?

EDIT FOR CLARITY: In the thrown exception I can see the line numbers in the StackTrace property. I'm assuming that means I have everything else I need.

Thanks in advance.

+1  A: 

did you try msdn example?
someone (via google) had the same issue...

Are you running a DEBUG version with the .pdb files accessible to the app? If not, you won't be able to get the line number.

edit:

have you thought of, when you are creating a new StackTrace, calling this ctor with fNeedFileInfo set to true?

Andreas Niedermair
read the question again.
Stimul8d
updated .......
Andreas Niedermair
Damn, people are quick with their answers now! I don't even know which of you was quickest with the right ctor. Thanks anywho. +1
Stimul8d
well - we are not counting peanuts here, do we? :)
Andreas Niedermair
+8  A: 

According to the documentation on the StackTrace constructor overload that takes an exception you can't expect line numbers when creating the StackTrace that way.

The StackTrace is created with the caller's current thread, and does not contain file name, line number, or column information.

To get the line numbers, you need to use the overload that takes a bool as well as the exception.

You also need symbol files (pdb) for line numbers. Symbol files are available for both debug and release builds.

Brian Rasmussen
Since I can see the line numbers in the exception.stacktrace string though doesn't that mean that i do have the pdb?
Stimul8d
I don't think this is a case of missing pdb since he's able to see the line numbers.
Gerrie Schenck
ahh, so it does; good call.
Stimul8d
too fast :) sry
Andreas Niedermair
Thinking about this, wouldn't it be better to make the standard StackFrame interface abstract and have a subclass (FileInfoStackFrame for example) which exposes the file information rather than have an overloaded constructor decide when those properties are appropriate? Seems like a poorly defined interface to me. Hmmm...
Stimul8d