C#中的运行时编译问题?

时间:2011-06-10 18:30:26

标签: c# runtime compilation

我想从http://pastehtml.com/view/awono3xoq.txt下载代码,将其保存为字符串,然后编译&单击按钮时运行它,但我似乎无法使下面的代码工作:

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 Microsoft.CSharp;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices; 

namespace ASV
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    public void compile()
    {
        CSharpCodeProvider myCodeProvider = new CSharpCodeProvider();
        ICodeCompiler myCodeCompiler = myCodeProvider.CreateCompiler();
        String [] referenceAssemblies = {"System.dll"};
        string myAssemblyName = "Assembly.exe";
        CompilerParameters myCompilerParameters = new CompilerParameters(referenceAssemblies, myAssemblyName);
        myCompilerParameters.GenerateExecutable = true;
        myCompilerParameters.GenerateInMemory = true;
        WebClient x = new WebClient();
        Stream y = x.OpenRead("http://pastehtml.com/view/awono3xoq.txt");
        StreamReader z = new StreamReader(y);
        string source = z.ReadToEnd();
        z.Close();
        y.Close();
        CompilerResults compres = myCodeCompiler.CompileAssemblyFromSource(myCompilerParameters, source);
        Process.Start("Assembly.exe");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        compile();
    }
}
}

我做错了什么(除了使用过多的陈述:P)?

1 个答案:

答案 0 :(得分:1)

如果您检查CompilerResults compres,则表明存在异常并且编译未成功,因此未写出Assembly.exe并且System.IO.FileNotFound存在Process.Start()例外

试试这个

public void compile()
{
    CSharpCodeProvider myCodeProvider = new CSharpCodeProvider();
    ICodeCompiler myCodeCompiler = myCodeProvider.CreateCompiler();
    string myAssemblyName = @"Assembly.exe";
    CompilerParameters myCompilerParameters = new CompilerParameters
                                                  {
                                                      OutputAssembly = myAssemblyName,
                                                      GenerateExecutable = true,
                                                      GenerateInMemory = true
                                                  };
    myCompilerParameters.ReferencedAssemblies.Add("System.dll");
    WebClient x = new WebClient();
    Stream y = x.OpenRead("http://pastehtml.com/view/awono3xoq.txt");
    StreamReader z = new StreamReader(y);
    string source = z.ReadToEnd();
    z.Close();
    y.Close();
    CompilerResults compres = myCodeCompiler.CompileAssemblyFromSource(myCompilerParameters, source);
    Process.Start(myAssemblyName);
}