bopin2020
3 min readJan 4, 2021

.NET compile dynamically with Roslyn(code generation using CSharpSyntaxRewriter)

Recently I was diving into Roslyn fields,I wished that it what I want about codes could be added into my template files. Well This not an English Grammer blog so Please ignore any grammatical mistaks. If you would like to keep track of me about .NET or other redteam techniques,please follow me @bopin2020.

Firstly We need one template file,here was relevant code:

Indeed there is no bopin variable,so our goal is to generate a variable in the specific class. And compiling dynamically it to convert into a WindowsApplication,we called success.exe for the moment. The final result like this:

I assumed you knew Roslyn,SyntaxTree and how to compile a couple of code with Roslyn. It’s so easy surely. Here are steps:

  • Parsing codes into one SyntaxTree
  • Add some references( like System.Windows.Forms.dll)
  • CSharpCompilation.Create() to compile targets

more details => here

My mainly purpose about writing this post is on Inserting code what I want into my template file. So let’s continue.

I believe you could know how to compile code with Roslyn, generating code is a bit complex.I read so many blogs,github code and visit stackoverflow more times for lasting three days, I put their links in the bottom named “reference”.

Okay,come back to our topic.How to insert our codes into template file?

we need to learn Microsoft.CodeAnalysis.CSharp.Syntax

We’d better to new a class inhert from CSharpSyntaxRewriter I learned it from here. Look at my steps:

  • using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
  • class ModifyClassDeclaration : CSharpSyntaxRewriter{
  • public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node){
  • }
  • }

The result is:

Maybe it looked like ugly,but nothing influence oncompiling.

In order to get this result,we need “new ModifyClassDeclaration” and then rebuild a new SyntaxTree,as SyntaxTree is a readonly SyntaxTree variable.

var result = new ModifyClassDeclaration().Visit(tree.GetRoot());

When running “Visit()” method,it called our override methods automatically to achieve our purpose.

And then rebuild a new SyntaxTree:

var newtree = CSharpSyntaxTree.ParseText(result.ToFullString());

The rest of steps are sample as above. The full version is here

Finally,We got success.exe file

##Reference

More details, see my learn notes: here

bopin2020

Learner | C2 developer | infosec researcher | redteamer