Dynamic C# code compilation in memory
Simple example how to compile C# code within a C#-Programm
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
public static class DynamicCompilation {
public static object CompileAndRun(string code) {
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.GenerateInMemory = true;
compilerParams.GenerateExecutable = false;
CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParams, code);
if (results.Errors.HasErrors) {
string errors = "";
foreach (CompilerError error in results.Errors) {
errors += error.ErrorText + "\n";
}
throw new Exception("Compilation failed:\n" + errors);
}
Assembly assembly = results.CompiledAssembly;
object instance = assembly.CreateInstance("DynamicCode");
MethodInfo method = instance.GetType().GetMethod("Main");
return method.Invoke(instance, null);
}
}
Calling the code
string code = "using System; public class DynamicCode { public static void Main() { Console.WriteLine(\"Hello World!\"); } }";
DynamicCompilation.CompileAndRun(code);
Whitelist Assemblies
You can also define a whitelist of assemblies to use, just add them to the ReferencedAssemblies
.
If you dont add assemblies, the compiler gives access to all assemblies on the system!
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("System.Core.dll");