Generating DLL assembly dynamically at run time

7wp picture 7wp · Mar 3, 2009 · Viewed 44.3k times · Source

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.

Answer

Rex M picture Rex M · Mar 3, 2009
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