原文:http://ms.mblogger.cn/minbear/posts/2530.aspx
C#原码动态编译功能实现之方法二~
using Microsoft.CSharp;
using System.CodeDom.Compiler;
CSharpCodeProvider _SCP = new CSharpCodeProvider();
CompilerParameters _CP = new CompilerParameters();
_CP.GenerateExecutable = false;
_CP.MainClass = "CodeCompile.RunExpression";
_CP.OutputAssembly = "RunExpression.dll";
_CP.IncludeDebugInformation = true;
_CP.ReferencedAssemblies.Add( "System.dll" );
_CP.GenerateInMemory = false;
_CP.WarningLevel = 3;
_CP.TreatWarningsAsErrors = false;
_CP.CompilerOptions = "/optimize";
_CP.TempFiles = new TempFileCollection("..", true);
_SCP.CreateCompiler().CompileAssemblyFromSource(_CP,this.txtCodeContent.Text);
//注:this.txtCodeContent.Text即为原代码内容,我的测试原码如下:
using System;
using System.IO;
namespace CodeCompile
{
///
/// RunExpression 的摘要说明。
///
public class RunExpression
{
public RunExpression()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void Run()
{
int i = 0;
int j = 1;
int m = i + j;
System.IO.StreamWriter _FS = new System.IO.StreamWriter(@"E:/1.txt",true);
_FS.Write(System.DateTime.Now.ToString("yyyy-MM-dd mm:ss"));
_FS.Close();
}
}
}