Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get source code filename of file from a type in debug build

Given a Type object in .NET, is it possible for me to get the source code filename? I know this would only be available in Debug builds and that's fine, I also know that I can use the StackTrace object to get the filename for a particular frame in a callstack, but that's not what I want.

But is it possible for me to get the source code filename for a given System.Type?

like image 232
Einar Egilsson Avatar asked Oct 28 '10 07:10

Einar Egilsson


1 Answers

I encountered a similar problem. I needed to found the file name and line number of a specific method with only the type of the class and the method name. I'm on an old mono .net version (unity 4.6). I used the library cecil, it provide some helper to analyse your pbd (or mdb for mono) and analyse debug symbols. https://github.com/jbevain/cecil/wiki

For a given type and method:

System.Type myType = typeof(MyFancyClass);
string methodName = "DoAwesomeStuff";

I found this solution:

Mono.Cecil.ReaderParameters readerParameters = new Mono.Cecil.ReaderParameters { ReadSymbols = true };
Mono.Cecil.AssemblyDefinition assemblyDefinition = Mono.Cecil.AssemblyDefinition.ReadAssembly(string.Format("Library\\ScriptAssemblies\\{0}.dll", assemblyName), readerParameters);

string fileName = string.Empty;
int lineNumber = -1;

Mono.Cecil.TypeDefinition typeDefinition = assemblyDefinition.MainModule.GetType(myType.FullName);
for (int index = 0; index < typeDefinition.Methods.Count; index++)
{
    Mono.Cecil.MethodDefinition methodDefinition = typeDefinition.Methods[index];
    if (methodDefinition.Name == methodName)
    {
        Mono.Cecil.Cil.MethodBody methodBody = methodDefinition.Body;
        if (methodBody.Instructions.Count > 0)
        {
            Mono.Cecil.Cil.SequencePoint sequencePoint = methodBody.Instructions[0].SequencePoint;
            fileName = sequencePoint.Document.Url;
            lineNumber = sequencePoint.StartLine;
        }
    }
}

I know it's a bit late :) but I hope this will help somebody!

like image 123
Tichau Avatar answered Nov 14 '22 21:11

Tichau