C#中实现在线编译为DLL

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using System.Diagnostics;
using UserClass;
namespace CSharpToDLL
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      //this.button1.Click += new System.EventHandler(this.button1_Click);
      //this.button2.Click += new System.EventHandler(this.button1_Click);
      User.UserName = "ABC";
      this.Text = User.getUserAge;
    }    
    private void button1_Click(object sender, EventArgs e)
    {

      CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
      string Output = "Out.DLL";
      Button ButtonObject = (Button)sender;
      textBox2.Text = "";
      System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
      //Make sure we generate an EXE, not a DLL
      parameters.GenerateExecutable = false; //true or false
      parameters.OutputAssembly = Output;
      CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, textBox1.Text);
      if (results.Errors.Count > 0)
      {

         textBox2.ForeColor = Color.Red;
        foreach (CompilerError CompErr in results.Errors)
        {
          textBox2.Text = textBox2.Text +
          "Line number " + CompErr.Line +
          ", Error Number: " + CompErr.ErrorNumber +
          ", '" + CompErr.ErrorText + ";" +
          Environment.NewLine + Environment.NewLine;
        }
      }
      else
      {
        //Successful Compile
        textBox2.ForeColor = Color.Blue;
        textBox2.Text = "Success!";
        //If we clicked run then launch our EXE
        if (ButtonObject.Text == "运行") Process.Start(Output);
      }
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
  }
}

posted @ 2011-12-25 22:33  风中刀客  阅读(472)  评论(0)    收藏  举报

用自己思想看世界 © 风中刀客