33

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.

Eric Dand
  • 1,081
  • 12
  • 36
7wp
  • 12,263
  • 19
  • 72
  • 99

3 Answers3

41
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

Rex M
  • 138,842
  • 31
  • 279
  • 313
  • Note: older versions of this code have an extra line of code which create a compiler from the provider using CSharpCodeProvider.CreateCompiler(). This is deprecated, you should call compile on the provider directly. – Andrew Hill Dec 28 '17 at 22:21
35

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));
    }
}
Lars A. Brekken
  • 22,325
  • 3
  • 24
  • 27
Anssssss
  • 2,795
  • 27
  • 37
5

Right now, your best bet is CSharpCodeProvider; the plans for 4.0 include "compiler as a service", which will make this fully managed.

Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
  • title of topic is "generating-dll-assembly-dynamically-at-run-time" NOT "generating-EXE-assembly-dynamically-at-run-time" your link description abut create exe at runtime. – Amin Ghaderi Apr 01 '15 at 08:30
  • 1
    @AminGhaderi and who said anything about exe? If you mean "but the code sample on MSDN creates an exe" - it will happily create dlls too; ultimately, the file package is *not* the interesting part of an assembly – Marc Gravell Apr 01 '15 at 08:31