代码动态编译:(DynamicCompile.cs)
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
//动态编译*.cs代码,并调用执行
namespace ConsoleApplication_DynamicCompile
{
public class Program
{
static void Main(string[] args)
{
// 设置编译参数
CompilerParameters param = new CompilerParameters();
param.ReferencedAssemblies.Add("System.dll");
param.GenerateExecutable = false;
param.GenerateInMemory = true;
// 动态编译字符串代码
string code = SourceCode();
Console.WriteLine(code);
CompilerResults result = new CSharpCodeProvider().CompileAssemblyFromSource(param, code);
if (result.Errors.HasErrors)
{
Console.WriteLine("编译错误:");
foreach (CompilerError err in result.Errors)
{
Console.WriteLine(err.ErrorText);
}
}
else
{
// 调用编译通过的程序集,创建的HelloWorld实例,中的函数OutPut
Assembly assembly = result.CompiledAssembly; // 获取已编译通过的程序集
object obj = assembly.CreateInstance("DynamicCompile.HelloWorld"); // 创建一个HelloWorld实例对象
MethodInfo method = obj.GetType().GetMethod("OutPut"); // 获取对象的OutPut方法
Console.WriteLine("\r\n// method.Invoke输出结果:");
method.Invoke(obj, null); // 调用obj对象的OutPut方法
}
Console.ReadLine();
}
// Hello world!代码
static string SourceCode()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("// HelloWorld源码:");
sb.AppendLine("using System;");
sb.AppendLine("namespace DynamicCompile");
sb.AppendLine("{");
sb.AppendLine(" public class HelloWorld");
sb.AppendLine(" {");
sb.AppendLine(" public void OutPut()");
sb.AppendLine(" {");
sb.AppendLine(" Console.WriteLine(\"Hello world!\");");
sb.AppendLine(" }");
sb.AppendLine("");
sb.AppendLine(" static void Main()");
sb.AppendLine(" {");
sb.AppendLine(" new HelloWorld().OutPut();");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine("}");
string code = sb.ToString();
return code;
}
}
}
2017-08-02:新增 调用类静态方法(DynamicCompile2)
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
//动态编译*.cs代码,并调用执行
namespace ConsoleApplication_DynamicCompile
{
public class Program
{
static void Main(string[] args)
{
// 设置编译参数
CompilerParameters param = new CompilerParameters();
param.ReferencedAssemblies.Add("System.dll");
param.GenerateExecutable = false;
param.GenerateInMemory = true;
// 动态编译字符串代码
string code = SourceCode();
Console.WriteLine(code);
CompilerResults result = new CSharpCodeProvider().CompileAssemblyFromSource(param, code);
if (result.Errors.HasErrors)
{
Console.WriteLine("编译错误:");
foreach (CompilerError err in result.Errors)
{
Console.WriteLine(err.ErrorText);
}
}
else
{
// 调用编译通过的程序集,创建的HelloWorld实例,中的函数OutPut
Assembly assembly = result.CompiledAssembly; // 获取已编译通过的程序集
object obj = assembly.CreateInstance("DynamicCompile.HelloWorld"); // 创建一个HelloWorld实例对象
MethodInfo method = obj.GetType().GetMethod("OutPut"); // 获取对象的OutPut方法
Console.WriteLine("\r\n// 调用类对象方法OutPut(),MethodInfo.Invoke输出结果:");
method.Invoke(obj, null); // 调用obj对象的OutPut方法
// 调用编译通过的程序集,HelloWorld中的静态方法Main
Assembly assembly2 = result.CompiledAssembly; // 获取已编译通过的程序集
Type type = assembly2.GetType("DynamicCompile.HelloWorld", true, true);
Console.WriteLine("\r\n// 调用类静态方法Main(),Type.InvokeMember输出结果:");
object[] arg = new object[] { "参数1", "参数2" };
object tmp = type.InvokeMember("Main", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, arg);
Console.WriteLine(tmp.ToString());
}
Console.ReadLine();
}
// Hello world!代码
static string SourceCode()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("// HelloWorld源码:");
sb.AppendLine("using System;");
sb.AppendLine("namespace DynamicCompile");
sb.AppendLine("{");
sb.AppendLine(" public class HelloWorld");
sb.AppendLine(" {");
sb.AppendLine(" public void OutPut()");
sb.AppendLine(" {");
sb.AppendLine(" Console.WriteLine(\"Hello world!\");");
sb.AppendLine(" }");
sb.AppendLine("");
sb.AppendLine(" public static String Main(String arg1, String arg2)");
sb.AppendLine(" {");
sb.AppendLine(" return \"传入参数:\" + arg1 + \" 、\" + arg2;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine("}");
string code = sb.ToString();
return code;
}
}
}
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
// 动态编译*.cs源码为可执行文件
namespace EXE_macker
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0) CompileExecutable(args[0]);
else
{
while (true)
{
Console.WriteLine("请拖动*.cs源码文件至此,编译EXE\r\n");
string fileName = Console.ReadLine();
CompileExecutable(fileName);
}
}
}
// 从源码文件codeFile,编译生成EXE
public static void CompileExecutable(String codeFile)
{
FileInfo source = new FileInfo(codeFile);
if (source.Extension.ToUpper(CultureInfo.InvariantCulture) != ".CS")
{
Console.WriteLine("仅支持编译以.cs为拓展名的源码!");
return;
}
String exeName = codeFile.Replace(".cs", ".exe").Replace(".CS", ".exe");
// 设置编译参数
CompilerParameters param = new CompilerParameters();
param.ReferencedAssemblies.Add("System.dll"); // 添加系统程序集
param.GenerateExecutable = true; // 编译时生成可执行文件
param.OutputAssembly = exeName; // 设置生成EXE的文件路径
param.GenerateInMemory = false;
param.TreatWarningsAsErrors = false;
// 从源码文件编译EXE
CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
CompilerResults result = provider.CompileAssemblyFromFile(param, codeFile);
if (result.Errors.Count > 0)
{
Console.WriteLine("编译出错:");
foreach (CompilerError ce in result.Errors)
Console.WriteLine(" {0}", ce.ToString());
}
else Console.WriteLine("编译完成!生成{0}\r\n", result.PathToAssembly);
}
}
}