using System; using System.Collections.Generic; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.CodeDom; using System.Globalization; using System.Reflection; /// <summary> /// 动态生成dll业务层 /// </summary> public class Createdll { /* 类调用方法 * StreamReader Reader = new StreamReader(Server.MapPath("~/Class1.cs"));//读取dll代码模板 string code = Reader.ReadToEnd();//读取 Createdll dll = new Createdll();//创建生成dll类 List<string> list=new List<string>();//创建引用组件list范型 list.Add("System.dll"); dll.dll(Server.MapPath("~/Bin/2.dll"), code, list);//生成 */ public Createdll() { //构造函数 } /// <summary> /// 动态生成dll /// </summary> /// <param name="path">生成位置</param> /// <param name="code">dll类代码</param> /// <param name="dll">需要添加的组件</param> /// <returns></returns> public int dll(string path,string code,List<string> dll) { //声明C#或的CodeDOM CSharpCodeProvider CP = new CSharpCodeProvider(); ICodeCompiler CCL = CP.CreateCompiler(); //设置编译参数,加入所需的组件 CompilerParameters CPs = new CompilerParameters(); foreach(string str in dll) { CPs.ReferencedAssemblies.Add(str); } CPs.GenerateInMemory = true; //生成位置 CPs.OutputAssembly = path; //开始编译 CodeSnippetCompileUnit CCU = new CodeSnippetCompileUnit(code); //返回编译结果 CompilerResults CRs = CCL.CompileAssemblyFromDom(CPs, CCU); return CRs.Errors.Count; } }