Considering that the debug data file is available (PDB) and by using either System.Reflection or another similar framework such as Mono.Cecil, how to retrieve programmatically the source file name and the line number where a type or a member of a type is declared.
For example, let's say you have compiled this file into an assembly:
C:MyProjectFoo.cs
1: public class Foo
2: {
3: public string SayHello()
4: {
5: return "Hello";
6: }
7: }
How to do something like:
MethodInfo methodInfo = typeof(Foo).GetMethod("SayHello");
string sourceFileName = methodInfo.GetSourceFile(); // ?? Does not exist!
int sourceLineNumber = methodInfo.GetLineNumber(); // ?? Does not exist!
sourceFileName would contain "C:MyProjectFoo.cs" and sourceLineNumber be equal to 3.
Update: System.Diagnostics.StackFrame
is indeed able to get that information, but only in the scope of current executing call stack. It means that the method must be invoked first. I would like to get the same info, but without invoking the type member.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…