如何使用C#在内存中执行.NET控制台应用程序? [英] How to execute a .NET console-application in memory using C#?
问题描述
我想从我的C#程序中直接从内存中执行一个包含另一个.NET可执行文件(一个C#控制台应用程序)的byte [],而无需接触磁盘.
From my C# program, I am trying to execute a byte[] containing another .NET executable (a C# console-application) directly from memory and without touching disk.
我知道这里也有类似的问题,还有一些关于如何做到这一点的好文章:
I am aware that there are similar questions posted here and also some good articles about how to do it like this one:
http://www.codeproject.com/Articles/13897/Load-an-EXE-File-and-Run-It-from-Memory
但是,它们都遇到相同的问题,但是它们只能用于在内存中执行Windows Forms应用程序,但是当我尝试执行Console-Applications时,它是行不通的.示例:
However, they all run into the same problem, they work BUT only for executing Windows Forms applications in memory, but when I try to execute Console-Applications it doesn't work. Example:
byte[] FileBytes = File.ReadAllBytes("C:\\MyTestProgram.exe"); // just for testing purposes
Assembly a = Assembly.Load(FileBytes);
MethodInfo m = a.EntryPoint;
m.Invoke(a.CreateInstance(m.Name), null);
当"MyTestProgram.exe"是Windows窗体时,它会完美执行.但是,当"MyTestProgram.exe"是控制台应用程序时,它将返回以下错误:
And when 'MyTestProgram.exe' is a Windows Form, it executes perfectly. But when 'MyTestProgram.exe' is a Console Application, it returns the following error:
未处理的异常:System.Reflection.TargetParameterCountException:参数计数不匹配"
"Unhandled exception: System.Reflection.TargetParameterCountException: Parameter count mismatch"
请注意,控制台应用程序未接收任何参数,所以这很奇怪...
Please note that the console application doesn't receives any arguments, so this is strange...
任何帮助将不胜感激:)
Any help would be very much appreciated :)
推荐答案
主要方法是静态的,您无需传递 Invoke
实例.您必须这样称呼它:
Main method is static, you don't need to pass Invoke
an instance. You have to call it like this:
var parameters = m.GetParameters().Length == 0 ? null : new[] { new string[0] };
m.Invoke(null, parameters);
此代码处理 Main()
和 Main(string [] args)
变体.
这篇关于如何使用C#在内存中执行.NET控制台应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!