Get the source code of a file name file from a type in a debug build

Given the Type object in .NET, is it possible to get the source code of the file name? I know that this will only be available in Debug assemblies, and that is fine, I also know that I can use the StackTrace object to get the file name for a specific frame in the call stack, but thatโ€™s not what I want.

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

+5
source share
3 answers

I ran into a similar problem. I needed to find the file name and line number of a specific method with only the class type and method name. I am in the old version of mono.net (unity 4.6). I used the cecil library, it provides some helper for analyzing your pbd (or mdb for mono) and analyzing debug symbols. https://github.com/jbevain/cecil/wiki

For this 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 this a bit later :), but I hope this helps someone!

+4
source

, # (, public partial class Foo ), " System.Type"? , , , .

@Darin Dimitrov: " ?" , , .

+3

, :

//must use the override with the single boolean parameter, set to true, to return additional file and line info

System.Diagnostics.StackFrame stackFrame = (new System.Diagnostics.StackTrace(true)).GetFrames().ToList().First();

//Careful:  GetFileName can return null even though true was specified in the StackTrace above.  This may be related to the OS on which this is running???

string fileName = stackFrame.GetFileName();
string process = stackFrame.GetMethod().Name + " (" + (fileName == null ? "" : fileName + " ") + fileLineNumber + ")";
+3

All Articles