See this article:
http://support.microsoft.com/kb/304655
Here's the sample code they provide:
var codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
var parameters = new CompilerParameters()
{
GenerateExecutable = true,
OutputAssembly = Output,
};
CompilerResults results = icc.CompileAssemblyFromSource(parameters, sourceString);
if (results.Errors.Count > 0)
{
foreach(CompilerError error in results.Errors)
{
textBox2.Text = textBox2.Text
+ "Line number " + error.Line
+ ", Error Number: " + error.ErrorNumber
+ ", '" + error.ErrorText + ";"
+ Environment.NewLine + Environment.NewLine
;
}
}
As Aliostad has mentioned in his answer, be careful with this solution, though. You will need to make sure your compiled code ends up in its own AppDomain
, otherwise you will experience memory leaks.
See this related question on how to load the code into a separate AppDomain
:
How can I prevent CompileAssemblyFromSource from leaking memory?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…