tags:

views:

78

answers:

2

Say you've got a MethodInfo, or any other sub-class of MemberInfo for that matter, in C#. Is it possible to retrieve the name of the file it was declared in and possibly the line numbers for where the declaration starts? This information has to exist somewhere in the debug-mode metadata since creating an instance of StackTrace will give you that information. Should I be looking in System.Diagnostics instead of System.Reflection?

+4  A: 

The information about line numbers is coming from symbol files (or "program database" .pdb) typically. Tools like FxCop use the symbol file to link the IL back to the source code. I googled the following API for you: http://msdn.microsoft.com/en-us/library/system.diagnostics.symbolstore.aspx

jdv
+1  A: 

You should use the System.Diagnostics Symbol classes to pull information from the .pdb files. Here is a good blog on it

Something like this might work:

using System;
using System.Diagnostics;

class Foo
{
static void Main()
{
    SmallFunc();
}

static void SmallFunc()
{
    PrintStack();
}
static void PrintStack()
{
    StackTrace st = new StackTrace(true); // true means get line numbers.
    foreach(StackFrame f in st.GetFrames()) {
        Console.Write(f);
    }
}
}
jjacka