C#动态加载创建程序集
2009-01-09 12:39
555 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.CodeDom.Compiler ; using Microsoft.CSharp ; using System.Reflection ; using System.IO ; namespace WpfApplication2 { class CodeDriver { private string prefix = "using System;" + "public static class Driver" + "{" + "public static void Run()" + "{" ; private string postfix = "}" + "}" ; public string ComplieAndRun( string input , out bool hasError ) { hasError = false ; string returnData = null ; CompilerResults results = null ; using( CSharpCodeProvider provider = new CSharpCodeProvider() ) { CompilerParameters options = new CompilerParameters() ; options.GenerateInMemory = true ; StringBuilder sb = new StringBuilder() ; sb.Append( prefix ) ; sb.Append( input ) ; sb.Append( postfix ) ; results = provider.CompileAssemblyFromSource( options , sb.ToString() ) ; } //如果编译出错 if( results.Errors.HasErrors ) { hasError = true ; StringBuilder errorMsg = new StringBuilder() ; foreach( CompilerError e in results.Errors ) { errorMsg.AppendFormat( "{0} {1}" , e.Line , e.ErrorText ) ; } returnData = errorMsg.ToString() ; } else { TextWriter temp = Console.Out ; StringWriter writer = new StringWriter() ; Console.SetOut( writer ) ; Type type = results.CompiledAssembly.GetType( "Driver" ) ; type.InvokeMember( "Run" , BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public , null , null ,null ) ; Console.SetOut( temp ) ; returnData = writer.ToString() ; } return returnData ; } } }
相关文章推荐
- C#动态程序集的加载、创建实例、序列化与反序列化
- C#动态程序集的加载、创建实例、序列化与反序列化
- C#动态程序集的加载、创建实例、序列化与反序列化
- C#动态创建和动态使用程序集、类、方法、字段等(二)
- C#创建windows服务:提示未能加载程序集,指定的路径找不到
- C#动态创建和动态使用程序集、类、方法、字段等(二)
- C#动态加载程序集(转)
- 应用程序配置和动态加载2----创建程序集
- C# 动态加载程序集dll (实现接口)
- 未能加载文件或程序集“sorttbls.nlp” 与 未能创建 Microsoft Visual C# 2008 编译器
- C#动态创建和动态使用程序集、类、方法、字段等
- C#动态创建和动态使用程序集、类、方法、字段等
- C#.Net 如何动态加载与卸载程序集(.dll或者.exe)6-----在不卸载程序域的前提下替换程序集文件。
- c# 动态编译创建程序集
- C# WinForm利用sideBar动态加载菜单栏,并创建菜单栏事件
- C#动态创建和动态使用程序集、类、方法、字段等
- c# 动态加载和卸载C#DLL程序集 C++程序集,
- C#动态创建和动态使用程序集、类、方法、字段等(一)
- C# WinForm利用sideBar动态加载菜单栏,并创建菜单栏事件
- c#.net 内存中 动态创建类型以及程序集