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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With