0

Hi i want to compile a class at runtime using CodeDom and generate in memory. How do i go about running the compiled code from memory?

My TextFile Resource:

using System.IO;
using System;

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

My actual application which compiles the textfile

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());
    }
}

The debugger simply says: 'Exe From Memory.vshost.exe' (Managed): Loaded 'r8ztr3t0' Since its loaded why doesnt the console window show?

1 Answer 1

1

All Invoke() does is that it calls the method, it doesn't create new application. And since you're running a windows application that doesn't have a console, the text isn't written anywhere.

If you want to show the console window from your application, you can use the Win32 AllocConsole() function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.