Generating DLL assembly dynamically at run time
Currently I have some code that is being generated dynamically. In other words, a C# .cs file is created dynamically by the program, and the intention is to include this C# file in another project.
The challenge is that I would like to generate a .DLL file instead of generating a C# .cs file so that it could be referenced by any kind of .NET application (not only C#) and therefore be more useful.
using System.CodeDom.Compiler;
using System.Diagnostics;
using Microsoft.CSharp;
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = "AutoGen.dll";
CompilerResults results = icc.CompileAssemblyFromSource(parameters, yourCodeAsString);
Adapted from http://support.microsoft.com/kb/304655
The non-deprecated way of doing it (using .NET 4.0 as previous posters mentioned):
using System.CodeDom.Compiler;
using System.Reflection;
using System;
public class J
{
public static void Main()
{
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = "AutoGen.dll";
CompilerResults r = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(parameters, "public class B {public static int k=7;}");
//verify generation
Console.WriteLine(Assembly.LoadFrom("AutoGen.dll").GetType("B").GetField("k").GetValue(null));
}
}