10

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.

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
EightyOne Unite
  • 11,665
  • 14
  • 79
  • 105

1 Answers1

18

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
  • 114,645
  • 34
  • 221
  • 317
  • Since I can see the line numbers in the exception.stacktrace string though doesn't that mean that i do have the pdb? – EightyOne Unite Feb 09 '10 at 12:22
  • I don't think this is a case of missing pdb since he's able to see the line numbers. – Gerrie Schenck Feb 09 '10 at 12:25
  • 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... – EightyOne Unite Feb 09 '10 at 15:06