CompilerParameters.GenerateInMemory

时间:2011-08-27 14:59:15

标签: c# reflection assemblies codedom

您好我想在运行时使用CodeDom编译一个类并在内存中生成。我如何从内存中运行已编译的代码?

我的TextFile资源:

using System.IO;
using System;

namespace Exe_From_Memory
{
    static class MemoryExe
    {
        static void Main()
        {
            string strText = "[TEXT]";
            Console.WriteLine(strText);
            Console.Read();
        }
    }
}

我编译文本文件的实际应用程序

private void exeButton_Click(object sender, EventArgs e)
{
    string text = textBox1.Text;
    string source;

    source = Properties.Resources.MemoryExe;
    source = source.Replace("[TEXT]", text);

    CompilerParameters _CompilerParameters = new CompilerParameters();

    _CompilerParameters.ReferencedAssemblies.Add("System.dll");
    _CompilerParameters.GenerateExecutable = true;
    _CompilerParameters.GenerateInMemory = true;

    _CompilerParameters.IncludeDebugInformation = false ;

    CSharpCodeProvider _CSharpCodeProvider = new CSharpCodeProvider();
    CompilerResults _CompilerResults = _CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, source);

    Assembly _Assembly = _CompilerResults.CompiledAssembly;
    MethodInfo mi = _Assembly.EntryPoint;
    object o = _Assembly.CreateInstance(mi.Name);
    mi.Invoke( o, null);

    foreach (CompilerError _CompilerError in _CompilerResults.Errors)
    {
        MessageBox.Show(_CompilerError.ToString());
    }
}

调试器只是说: 'Exe From Memory.vshost.exe'(管理):已加载'r8ztr3t0' 因为它加载了为什么控制台窗口不显示?

1 个答案:

答案 0 :(得分:1)

所有Invoke()都会调用方法,它不会创建新的应用程序。而且由于您运行的是没有控制台的Windows应用程序,因此不会在任何地方写入文本。

如果要显示应用程序中的控制台窗口you can use the Win32 AllocConsole() function