compile c# code at runtime

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hallo,
I found a lot of examples about compiling c# code at runtime. But none of them helped me. What I am trying to do is to compile and run some c# code. The problem is that this code uses dlls, such as "WindowsBase.dll", that apparently,
cannot be found while compiling the code. Basically, I get this compiler error:

Compile error: rnerror CS0006: Metadata file WindowsBase.dll could not be found.
The function I am using to Compile the code is this:
<pre class="prettyprint public static CompilerResults CompileCode(Dictionary<string, string> code)
{
var compilerParams = new CompilerParameters
{
GenerateInMemory = true,
TreatWarningsAsErrors = false,
GenerateExecutable = false,
CompilerOptions = "/optimize",
};
string[] references = {
"System.dll",
"System.Data.dll",
"System.Xml.dll",
"mscorlib.dll",
"System.Windows.Forms.dll",
"System.Drawing.dll",
"WindowsBase.dll"
};
compilerParams.ReferencedAssemblies.AddRange(references);
var provider = new CSharpCodeProvider();
return provider.CompileAssemblyFromSource(compilerParams, code.Values.ToArray());
}[/code]
All other assemblies that I am adding do not cause any problem. Only the "WindowsBase.dll" is not found.
Does anyone knows how to properly add references to code that need to be compiled at runtime ? What about if I wanted to add an external dll ? (not part of the frameword, such as my myDLL.dll, that is in c:tempmyDLL.dll)
Thanks

View the full article
 
I found similar problem on stackoverflowDOTcom (question Missing assembly references in dynamically compiled code) and solution is:

CSharpCodeProvider defaults to version 2.0 that have no support for generics or linq. The following fixed the problem:
var provider = new CSharpCodeProvider( new Dictionary<String, String>{{ "CompilerVersion","v3.5" }});
 
Back
Top