using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.CodeDom;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CreateCode();
}
private bool CreateCode()
{
Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.ICodeCompiler comp = provider.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.ReferencedAssemblies.Add("system.data.dll");
cp.ReferencedAssemblies.Add("system.xml.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
StringBuilder strConsole = new StringBuilder();
strConsole.Append("using System;");
strConsole.Append("using System.Collections.Generic;");
strConsole.Append("using System.Text;");
strConsole.Append("namespace ConsoleTest");
strConsole.Append("{");
strConsole.Append("class Program");
strConsole.Append("{");
strConsole.Append("static void Main(string[] args)");
strConsole.Append("{");
strConsole.Append("Console.WriteLine(\"this is ok !\");");
strConsole.Append("Console.ReadLine();");
strConsole.Append("}");
strConsole.Append("}");
strConsole.Append("}");
System.CodeDom.Compiler.CompilerResults cr = comp.CompileAssemblyFromSource(cp, strConsole.ToString());
System.CodeDom.Compiler.TempFileCollection tf = new System.CodeDom.Compiler.TempFileCollection(@"E:\工作\RegiestEventHandlers\Test\Test\bin\Debug", true);
cr.PathToAssembly = @"E:\工作\RegiestEventHandlers\Test\Test\bin\Debug";
System.Diagnostics.Debug.Write(strConsole.ToString());
if (cr.Errors.HasErrors)
{
System.Text.StringBuilder errorMsg = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError err in cr.Errors)
{
errorMsg.Append(err.ErrorText);
}
System.Diagnostics.Debug.WriteLine(errorMsg.ToString());
throw new System.Exception("编译错误: " + errorMsg.ToString());
}
else
{
return true;
}
}
}
}
我想用C#代码动态编译生成程序集,但是代码执行是成功的,就是找不到生成的这个ConsoleTest.exe文件.。怎么样才能生成这个文件,到我指定的目录下。