C# 动态生成DLL

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.CodeDom;
using Microsoft.CSharp;
using System.IO;
using System.CodeDom.Compiler;
using System.Text;
using System.Reflection;

/// <summary>
/// Summary description for Create_Dll
/// </summary>
public class Create_Dll
{
 public Create_Dll()
 {
  //
  // TODO: Add constructor logic here
  //
 }
    /// <summary>
    /// 创建数据库MODEL类
    /// </summary>
    /// <param name="classNamespace">实体类名称</param>
    /// <returns></returns>
    public void Create_Model_DLL(string classNamespace)
    {   String Dll_file_Name = "";
        Dll_file_Name = classNamespace+"MODEL.dll";
        //生成一个可编译的单元,这是最根部的东西
        CodeCompileUnit compunit = new CodeCompileUnit();

        //  创建编译器实例//设置编译器对象
        CSharpCodeProvider csprovider = new CSharpCodeProvider();
        ICodeCompiler complier = csprovider.CreateCompiler();
        ICodeGenerator gen = csprovider.CreateGenerator();   //生成CS文件
        //  设置编译参数。 
        CompilerParameters paras = new CompilerParameters();
        paras.GenerateExecutable = false;   //编译成exe还是dll
        paras.GenerateInMemory = false;           //是否写入内存,不写入内存就写入磁盘
        paras.OutputAssembly = "d:\\" + Dll_file_Name;         //输出路径
        paras.IncludeDebugInformation = false; //是否产生pdb调试文件      默认是false

   
        paras.ReferencedAssemblies.Add("System.dll");//添加引用DLL
        paras.ReferencedAssemblies.Add("System.Data.dll");//添加引用DLL
     

        StringBuilder Greef_Song_Class_Source = new StringBuilder();
    
        Greef_Song_Class_Source.Append("using System;\r\n");
        Greef_Song_Class_Source.Append("using System.Collections.Generic;\r\n");
        Greef_Song_Class_Source.Append("using System.Text;\r\n");
        Greef_Song_Class_Source.Append("using System.Data;\r\n");
        Greef_Song_Class_Source.Append("using System.Data.SqlClient;\r\n");
     
         //#region 命名空间及类名
        Greef_Song_Class_Source.Append("namespace " + classNamespace +".MODEL \r\n");
        Greef_Song_Class_Source.Append("{ \r\n");
     
        MYSQL_SQLDB SQLDB = new MYSQL_SQLDB();
        DataTable dt = new DataTable();
        DataTable dt1 = new DataTable();
        dt1.Clear();
        dt1 = SQLDB.Get_DataTable_By_ExecuteSQL("show tables");
          //类定义开始
         
        foreach (DataRow DB_Table_Names_dr in dt1.Rows)
        {
            //定义类开始
            Greef_Song_Class_Source.Append("    [Serializable()]   \r\n ");
            Greef_Song_Class_Source.Append("    public class " + classNamespace + "_MODEL_" + DB_Table_Names_dr[0].ToString() + "\r\n");
            Greef_Song_Class_Source.Append("    {  \r\n");
          
            dt.Clear();
            dt = SQLDB.Get_DataTable_By_ExecuteSQL("desc " + DB_Table_Names_dr[0].ToString().ToString() + "");
            foreach (DataRow dr in dt.Rows)
            {
                //定义字段
                Greef_Song_Class_Source.Append("        /// <summary> \r\n");
                Greef_Song_Class_Source.Append("        /// 此字段为数据表(" + DB_Table_Names_dr[0].ToString() + ")中的字段:" + dr[0].ToString() + "\r\n");
                Greef_Song_Class_Source.Append("        /// </summary> \r\n");
                Greef_Song_Class_Source.Append("        public String  "+dr[0].ToString() + ";                                                       \r\n");
                //定义字段结束
               // 定义属性
                Greef_Song_Class_Source.Append("       [System.ComponentModel.DisplayName(\"此属性为:数据表(" + DB_Table_Names_dr[0].ToString() + ")中的字段:" + dr[0].ToString() + "\")]     \r\n");
                Greef_Song_Class_Source.Append("        public String " + DB_Table_Names_dr[0].ToString() + "_" + dr[0].ToString() + "                 \r\n");
                Greef_Song_Class_Source.Append("      {" +"                                                                                                      \r\n");
                //获取属性值
                Greef_Song_Class_Source.Append("           get                                                                                                   \r\n");
                Greef_Song_Class_Source.Append("              {                                                                                                  \r\n");
                Greef_Song_Class_Source.Append("               return  "  + dr[0].ToString() + " ;                                                    \r\n");
                Greef_Song_Class_Source.Append("               }                                                                                                 \r\n");
                //获取属性值结束
                //设定属性值
                Greef_Song_Class_Source.Append("           set                                                                                                   \r\n");
                Greef_Song_Class_Source.Append("              {                                                                                                  \r\n");
                Greef_Song_Class_Source.Append("                " + dr[0].ToString() + " =value;                                                    \r\n");
                Greef_Song_Class_Source.Append("               }                                                                                                 \r\n");
                //设定属性值结束
                Greef_Song_Class_Source.Append("      }                                                                                                          \r\n");
                //定义属性结束
        
            }
            Greef_Song_Class_Source.Append("   }         \r\n");
            //类定义结束

        }
      
        Greef_Song_Class_Source.Append("}            \r\n");
        CompilerResults result = complier.CompileAssemblyFromSource(paras, Greef_Song_Class_Source.ToString());
      
     
    }
    public string Create_DAL_DLL(string classNamespace)
    {
        //string classNamespace/命名空间
        //string className 类名或表名
        String Dll_file_Name = "";
        Dll_file_Name = classNamespace + "DAL.dll";
        //生成一个可编译的单元,这是最根部的东西
        CodeCompileUnit compunit = new CodeCompileUnit();

        //  创建编译器实例//设置编译器对象
        CSharpCodeProvider csprovider = new CSharpCodeProvider();
        ICodeCompiler complier = csprovider.CreateCompiler();
        ICodeGenerator gen = csprovider.CreateGenerator();   //生成CS文件
        StreamWriter sw = new StreamWriter(@"c:\testywm.cs", false);
        gen.GenerateCodeFromCompileUnit(compunit, sw, new CodeGeneratorOptions());


        //  设置编译参数。 
        CompilerParameters paras = new CompilerParameters();
        paras.GenerateExecutable = false;   //编译成exe还是dll
        paras.GenerateInMemory = false;           //是否写入内存,不写入内存就写入磁盘
        paras.OutputAssembly = "d:\\" + Dll_file_Name;         //输出路径
        paras.IncludeDebugInformation = false; //是否产生pdb调试文件      默认是false


        paras.ReferencedAssemblies.Add("System.dll");//添加引用DLL
        paras.ReferencedAssemblies.Add("System.Data.dll");//添加引用DLL
        paras.ReferencedAssemblies.Add("D:\\" + classNamespace + "MODEL.dll");//添加引用DLL
          

        StringBuilder Greef_Song_Class_Source = new StringBuilder();

        Greef_Song_Class_Source.Append("using System;\r\n");
        Greef_Song_Class_Source.Append("using System.Collections.Generic;\r\n");
        Greef_Song_Class_Source.Append("using System.Text;\r\n");
        Greef_Song_Class_Source.Append("using System.Data;\r\n");
        Greef_Song_Class_Source.Append("using System.Data.SqlClient;\r\n");
        Greef_Song_Class_Source.Append("using " + classNamespace + ".MODEL;\r\n");
        
        //#region 命名空间及类名
        Greef_Song_Class_Source.Append("namespace " + classNamespace + ".DAL \r\n");
        Greef_Song_Class_Source.Append("{ \r\n");

        MYSQL_SQLDB SQLDB = new MYSQL_SQLDB();
        DataTable dt = new DataTable();
        DataTable dt1 = new DataTable();
        dt1.Clear();
        dt1 = SQLDB.Get_DataTable_By_ExecuteSQL("show tables");
        //类定义开始

        foreach (DataRow DB_Table_Names_dr in dt1.Rows)
        {
            //定义类开始
            Greef_Song_Class_Source.Append("    [Serializable()]   \r\n ");
            Greef_Song_Class_Source.Append("    public class " + classNamespace + "_DAL_" + DB_Table_Names_dr[0].ToString() + "\r\n");
            Greef_Song_Class_Source.Append("    {  \r\n");

           
                //定义字段
            Greef_Song_Class_Source.Append("       public " + classNamespace + "_MODEL_" + DB_Table_Names_dr[0].ToString() + " Member = new " + classNamespace + "_MODEL_" + DB_Table_Names_dr[0].ToString() + "();                                                       \r\n");
                //定义字段结束
                      
            Greef_Song_Class_Source.Append("   }         \r\n");
            //类定义结束

        }

        Greef_Song_Class_Source.Append("}            \r\n");

        sw.Write(Greef_Song_Class_Source.ToString());   //输出文件
        sw.Close();    //关闭文件


        //  System.Diagnostics.Debug.WriteLine(Greef_Song_Class_Source.ToString()); // 调试用。注释掉
        //  编译代码。 
        CompilerResults result = complier.CompileAssemblyFromSource(paras, Greef_Song_Class_Source.ToString());
        //  获取编译后的程序集。

        //Assembly assembly = result.CompiledAssembly;

        return Greef_Song_Class_Source.ToString();
        ////  动态调用方法。
        //object eval = assembly.CreateInstance(className);
        //MethodInfo method = eval.GetType().GetMethod(methodName);
        // object reobj = "生成dll成功";// method.Invoke(eval, null);
        //GC.Collect();
        // return reobj;

    }

 


}

posted @ 2012-07-19 14:15  greefsong  阅读(683)  评论(0编辑  收藏  举报