Ali Ersöz
Ali Ersöz

Reputation: 16086

Is there a way to load a class file to assembly in runtime?

I'm trying to do something that gets a cs file in runtime from user make it meaningful to assembly get its properties, methods etc.

Is there a way to do this by reflection in C#?

Upvotes: 8

Views: 3823

Answers (2)

edosoft
edosoft

Reputation: 17271

To compile a file on the fly you'll need to do something along these lines (where sourceCode is a string containg the code to compile):

CodeDomProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler compiler = codeProvider.CreateCompiler();

// add compiler parameters
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.CompilerOptions = "/target:library /optimize";
compilerParams.GenerateExecutable = false;
compilerParams.GenerateInMemory = true;         
compilerParams.IncludeDebugInformation = false;
compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");

// compile the code
CompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, sourceCode);

Upvotes: 10

Jon Skeet
Jon Skeet

Reputation: 1499750

You can compile it reasonably easily using the CSharpCodeProvider. You can download the source code for my snippet compiler, Snippy, from the C# in Depth web site. That uses CSharpCodeProvider, so you could use it as sample code.

Upvotes: 4

Related Questions