Simple code for creating the assemblies dynamically from a C# code file.
public bool CompileSource(string sourceFile, string targetAssembly, string [] references)
{
// delete existing assembly first
if (File.Exists(targetAssembly))
{
try
{
// this might fail if assembly is in use
File.Delete(targetAssembly);
}
catch (Exception ex)
{
this.ErrorMessage = ex.Message;
return false;
}
}
// read the C# source file
StreamReader sr = new StreamReader(sourceFile);
string fileContent = sr.ReadToEnd();
sr.Close();
// set up compiler and add required references
ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters parameter = new CompilerParameters();
parameter.OutputAssembly = targetAssembly;
foreach(string reference in references)
{
parameter.ReferencedAssemblies.Add(reference);
}
// Do it: Final compilation to disk
CompilerResults results = compiler.CompileAssemblyFromFile(parameter, sourceFile);
if (File.Exists(targetAssembly))
return true;
// flatten the compiler error messages into a single string
foreach (CompilerError err in results.Errors)
{
this.ErrorMessage += err.ToString() + "\r\n";
}
return false;
}
{
// delete existing assembly first
if (File.Exists(targetAssembly))
{
try
{
// this might fail if assembly is in use
File.Delete(targetAssembly);
}
catch (Exception ex)
{
this.ErrorMessage = ex.Message;
return false;
}
}
// read the C# source file
StreamReader sr = new StreamReader(sourceFile);
string fileContent = sr.ReadToEnd();
sr.Close();
// set up compiler and add required references
ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters parameter = new CompilerParameters();
parameter.OutputAssembly = targetAssembly;
foreach(string reference in references)
{
parameter.ReferencedAssemblies.Add(reference);
}
// Do it: Final compilation to disk
CompilerResults results = compiler.CompileAssemblyFromFile(parameter, sourceFile);
if (File.Exists(targetAssembly))
return true;
// flatten the compiler error messages into a single string
foreach (CompilerError err in results.Errors)
{
this.ErrorMessage += err.ToString() + "\r\n";
}
return false;
}