I'm able to use Mono.Cecil and ICSharpCode.Decompiler to generate the code for a type or an assembly.
But if I try to generate the code for a single method I'll get an error "Object reference not set to an instance of an object."
Can you guys give me any hints about this? Thanks ahead for all the help.
Code to generate code for all the types inside an assembly:
DirectoryInfo di = new DirectoryInfo(appPath);
FileInfo[] allAssemblies = di.GetFiles("*.dll");
foreach (var assemblyFile in allAssemblies)
{
string pathToAssembly = assemblyFile.FullName;
System.Reflection.Assembly assembly = System.Reflection.Assembly.ReflectionOnlyLoadFrom(pathToAssembly);
Mono.Cecil.AssemblyDefinition assemblyDefinition = Mono.Cecil.AssemblyDefinition.ReadAssembly(pathToAssembly,parameters);
AstBuilder astBuilder = null;
foreach (var typeInAssembly in assemblyDefinition.MainModule.Types)
{
if (typeInAssembly.IsPublic)
{
Console.WriteLine("T:{0}", typeInAssembly.Name);
//just reset the builder to include only code for a single type
astBuilder = new AstBuilder(new ICSharpCode.Decompiler.DecompilerContext(assemblyDefinition.MainModule));
astBuilder.AddType(typeInAssembly);
StringWriter output = new StringWriter();
astBuilder.GenerateCode(new PlainTextOutput(output));
string result = output.ToString();
output.Dispose();
}
}
}
Code to generate code for all the public methods inside an assembly:
DirectoryInfo di = new DirectoryInfo(appPath);
FileInfo[] allAssemblies = di.GetFiles("*.dll");
foreach (var assemblyFile in allAssemblies)
{
string pathToAssembly = assemblyFile.FullName;
System.Reflection.Assembly assembly = System.Reflection.Assembly.ReflectionOnlyLoadFrom(pathToAssembly);
Mono.Cecil.AssemblyDefinition assemblyDefinition = Mono.Cecil.AssemblyDefinition.ReadAssembly(pathToAssembly,parameters);
AstBuilder astBuilder = null;
foreach (var typeInAssembly in assemblyDefinition.MainModule.Types)
{
if (typeInAssembly.IsPublic)
{
Console.WriteLine("T:{0}", typeInAssembly.Name);
foreach (var method in typeInAssembly.Methods)
{
//just reset the builder to include only code for a single method
astBuilder = new AstBuilder(new ICSharpCode.Decompiler.DecompilerContext(assemblyDefinition.MainModule));
astBuilder.AddMethod(method);
if (method.IsPublic && !method.IsGetter && !method.IsSetter && !method.IsConstructor)
{
Console.WriteLine("M:{0}", method.Name);
StringWriter output = new StringWriter();
astBuilder.GenerateCode(new PlainTextOutput(output));
string result = output.ToString();
output.Dispose();
}
}
}
}
}