执行程序
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sourceCode = File.ReadAllText(@text.cs文件路径, Encoding.UTF8);
MessageBox.Show(sourceCode);
// 创建编译器选项
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.GenerateInMemory = true; // 将程序集生成到内存中
compilerParams.GenerateExecutable = false; // 生成的程序集为类库
// 添加需要引用的程序集,例如System.dll
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
// 创建C#编译器
CSharpCodeProvider provider = new CSharpCodeProvider();
// 编译C#代码
CompilerResults compilerResults = provider.CompileAssemblyFromSource(compilerParams, sourceCode);
// 检查编译是否成功
if (compilerResults.Errors.HasErrors)
{
// 输出编译错误信息
foreach (CompilerError error in compilerResults.Errors)
{
//Console.WriteLine("Error: {0}", error.ErrorText);
MessageBox.Show( error.ErrorText);
}
}
else
{
// 获取编译后的程序集
Assembly assembly = compilerResults.CompiledAssembly;
// 创建动态类的实例并调用其中的方法
dynamic dynamicClass = assembly.CreateInstance("Program");//test.cs的类名
var ret = dynamicClass.PrintOut(99);//test.cs的函数和参数
MessageBox.Show(ret);//test.cs的PrintOut函数返回值
}
}
}
}
test.cs文件
//代码模板案例
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
//Here is class place
//===Class===
public class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
public void Main(string show)
{
MessageBox.Show(show);
//Here is code body place
//===Code===
}
public string PrintOut(int tot)
{
string ret="";
for(int i=0;i<=tot;i++)
{
ret+=i.ToString()+":";
}
return ret;
}
}
1095

被折叠的 条评论
为什么被折叠?



