c#中要运行文本文件中的c#代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Globalization;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Text;
using System.Windows.Forms;
namespace Test
{
public partial class Form9 : Form
{
public Form9()
{
InitializeComponent();
}
void Run()
{
// 1.CodeComplier
CodeDomProvider objICodeCompiler = CodeDomProvider.CreateProvider("CSharp");
// 2.CompilerParameters 添加多个引用
CompilerParameters objCompilerParameters = new CompilerParameters();
objCompilerParameters.ReferencedAssemblies.Add("System.dll");
objCompilerParameters.GenerateExecutable = false;
objCompilerParameters.GenerateInMemory = true;
// 3.CompilerResults
CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode());
if (cr.Errors.HasErrors)
{
Console.WriteLine("编译错误:");
foreach (CompilerError err in cr.Errors)
{
Console.WriteLine(err.ErrorText);
}
}
else
{
// 通过反射,调用HelloWorld的实例
Assembly objAssembly = cr.CompiledAssembly;
object objHelloWorld = objAssembly.CreateInstance("DynamicCodeGenerate.HelloWorld");
MethodInfo objMI = objHelloWorld.GetType().GetMethod("OutPut");
MessageBox.Show(Convert.ToString(objMI.Invoke(objHelloWorld, null)));
}
}
static string GenerateCode()
{
StringBuilder sb = new StringBuilder();
sb.Append("using System;");
sb.Append(Environment.NewLine);
sb.Append("namespace DynamicCodeGenerate");
sb.Append(Environment.NewLine);
sb.Append("{");
sb.Append(Environment.NewLine);
sb.Append(" public class HelloWorld");
sb.Append(Environment.NewLine);
sb.Append(" {");
sb.Append(Environment.NewLine);
sb.Append(" public string OutPut()");
sb.Append(Environment.NewLine);
sb.Append(" {");
sb.Append(Environment.NewLine);
sb.Append(" return \"Hello world!\";");
sb.Append(Environment.NewLine);
sb.Append(" }");
sb.Append(Environment.NewLine);
sb.Append(" }");
sb.Append(Environment.NewLine);
sb.Append("}");
string code = sb.ToString();
Console.WriteLine(code);
Console.WriteLine();
return code;
}
private void Form9_Load(object sender, EventArgs e)
{
Run();
}
}
}
以下是msdn上的文章,原文(http://support.microsoft.com/kb/304655)
.NET Framework 提供了 ICodeCompiler 编译器执行接口。CSharpCodeProvider 类实现此接口,并提供对 C# 代码生成器和代码编译器的实例的访问。下面的代码示例创建 CSharpCodeProvider 的实例,并使用它来获取对 ICodeCompiler 接口的引用。
CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler();
在您有了对 ICodeCompiler 接口的引用后可以使用它来编译源代码。 您将通过使用 CompilerParameters 类将参数传递给编译器。 下面是一个示例:
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.OutputAssembly = Output; CompilerResults results = icc.CompileAssemblyFromSource(parameters,SourceString);
上面的代码使用 CompilerParameters 对象告诉的编译器您要生成的可执行文件 (相对于 DLL) 和要输出到磁盘生成的程序集。 在调用 CompileAssemblyFromSource 是获取编译程序集的位置。 此方法将参数对象,并在源代码是字符串。 编译代码后,您可以检查是否有任何编译错误,请参阅。 使用从 CompileAssemblyFromSource,即 CompilerResults 对象返回的值。 此对象包含包含在编译过程中出现的所有错误的一个错误集合集合。
if (results.Errors.Count > 0) { foreach(CompilerError CompErr in results.Errors) { textBox2.Text = textBox2.Text + "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } }
private void button1_Click(object sender, System.EventArgs e) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); string Output = "Out.exe"; Button ButtonObject = (Button)sender; textBox2.Text = ""; System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); //Make sure we generate an EXE, not a DLL parameters.GenerateExecutable = true; parameters.OutputAssembly = Output; CompilerResults results = icc.CompileAssemblyFromSource(parameters, textBox1.Text); if (results.Errors.Count > 0) { textBox2.ForeColor = Color.Red; foreach (CompilerError CompErr in results.Errors) { textBox2.Text = textBox2.Text + "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } } else { //Successful Compile textBox2.ForeColor = Color.Blue; textBox2.Text = "Success!"; //If we clicked run then launch our EXE if (ButtonObject.Text == "Run") Process.Start(Output); } } Add the beginning of the file, add these using statements: using System.CodeDom.Compiler; using System.Diagnostics; using Microsoft.CSharp;
private void button1_Click(object sender, System.EventArgs e) { CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp"); string Output = "Out.exe"; Button ButtonObject = (Button)sender; textBox2.Text = ""; System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); //Make sure we generate an EXE, not a DLL parameters.GenerateExecutable = true; parameters.OutputAssembly = Output; CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, textBox1.Text); if (results.Errors.Count > 0) { textBox2.ForeColor = Color.Red; foreach (CompilerError CompErr in results.Errors) { textBox2.Text = textBox2.Text + "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } } else { //Successful Compile textBox2.ForeColor = Color.Blue; textBox2.Text = "Success!"; //If we clicked run then launch our EXE if (ButtonObject.Text == "Run") Process.Start(Output); } } Add the beginning of the file, add these using statements: using System.CodeDom.Compiler; using System.Diagnostics;
public Form1() { InitializeComponent(); this.button1.Click += new System.EventHandler(this.button1_Click); this.button2.Click += new System.EventHandler(this.button1_Click); }
using System; namespace HelloWorld { /// <summary> /// Summary description for Class1. /// </summary> class HelloWorldClass { static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.ReadLine(); } } }