I decided to write a simplified version of Jeff Keys’ most excellent Snippet Compiler to facilitate some experiments that I’ve been working on today. I absolutely love how easy it is to compile in-memory assemblies using System.CodeDom and friends:
private CompilerResults Compile()
{
CodeDomProvider provider = new CSharpCodeProvider();
ICodeCompiler compiler = provider.CreateCompiler();
CompilerParameters parameters = new CompilerParameters();
parameters.WarningLevel = 4;
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.ReferencedAssemblies.Add("System.Web.Services.dll");
parameters.ReferencedAssemblies.Add("System.Xml.dll");
parameters.ReferencedAssemblies.Add("System.dll");
return compiler.CompileAssemblyFromSource(parameters, textBoxSource.Text);
}
3 archived reader comments
Girish (2004-10-19)
Oh! wow!
Richard Poole (2004-10-20)
Don’t get me wrong, it’s a fantastic bunch of classes but it feels like these classes wrap the console compiler (csc.exe) instead of the actual compiler implementation that csc.exe uses (hence CompilerResults.Output being a StringCollection that is equivalent to the output of csc.exe).
I think it would have been a little bit nicer if we had access to Microsoft.CSharp.CSharpCompiler (csc.exe’s internal compiler implementation) instead of Microsoft.VisualStudio.CSharpCompilerConsole (csc.exe).
Also maybe that would solve the problem of it generating temporary files where you are restricted to read-only media.
I don’t think I explained that very well. Alcohol, don’t you hate it. :/
Disclaimer: The class names depicted in this posting are entirely fictional and bare no resemblence to those of the Microsoft(r) .NET(r) Framework.
John Lam (2004-10-21)
I just spied csc.exe flying by using procexp - yuck. I agree - it would be much better if they exposed the compiler directly. However, I hear that folks who build compilers rely on process recycling to kill extraneous state at the end of the compilation :(