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 Mai开发者_StackOverflow中文版n()
{
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?
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.
精彩评论