Professor of programming
Professor of programming

Reputation: 3073

How to dynamically compile source files into assembly in C#

I am aware of a class called AssemblyBuilder, and I would have thought I could use it to pass a folder containing C# source files, or pass a single C# source file to it in order to compile the source into an assembly (.dll) which can then be referenced in a config file.

I'm aware of csc.exe which can compile C#, and I'm effectively looking for a way to replicate this dynamically.

I couldn't figure out how to use AssemblyBuilder, or whether this is the wrong class to be using, or whether I should be doing something similar to the following: http://support.microsoft.com/kb/304655

Can you point me in the right direction please.

Upvotes: 1

Views: 1497

Answers (1)

user1334319
user1334319

Reputation:

You might want to look into CodeDomProvider

Example snippet:

CompilerParameters parms = new CompilerParameters
                                           {
                                               GenerateExecutable = false,
                                               GenerateInMemory = true,
                                               IncludeDebugInformation = false
                                           };

            parms.ReferencedAssemblies.Add("System.dll");
            parms.ReferencedAssemblies.Add("System.Data.dll");
            CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp"); 

            return compiler.CompileAssemblyFromSource(parms, source); 

Warning: assemblies built dynamically in this fashion won't be handled by the garbage collector.

Upvotes: 2

Related Questions