How to parse an C# assembly and extract every method
For my application I'd like to parse through an assembly and extract every method and store the name of the method and the source code in one of my objects (I defined in my code).
开发者_开发知识库where should I start to implement that?
EDIT: From the answers & comments i saw that it is not so easy to get source code from the assemblies. Then where should I start if I want to get source code from source code files that are not in my current solution (visual studio)?
The assembly doesn't contain the source code. You might be able to extract the IL, but without tools like reflector or ildasm that isn't especially helpful.
To obtain the method names, just something like:
var assembly = Assembly.GetExecutingAssembly();
var names = (from type in assembly.GetTypes()
from method in type.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static)
select type.FullName + ":" + method.Name).Distinct().ToList();
To retrieve this debugging information, use the Common Compiler Infrastructure: Metadata API project.
This allows you to read the .pdb
files (the files containing the debugging information like source file and line number).
First you need to find all the types.
See here to do that.
Then you can need to find all the methods for each types.
See here to do that.
If you need an example to bring it all together let me know.
I'm not sure how to get the source code, but if you're trying to get information about the methods, you should use reflection.
MethodInfo[] methodInfos = typeof(MyClass).GetMethods(BindingFlags.Public |
BindingFlags.Static);
精彩评论