Search code examples
c#.netdllcode-generation

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.


Solution

  • 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