C#从内存加载.net可执行文件

时间:2017-07-13 12:24:02

标签: c#

我正在通过WebClient将DLL流式传输到客户端,我正在尝试将我的.net可执行文件直接加载到内存中并通过将其作为程序集加载来执行它。此可执行文件是一个Windows窗体,它创建DirectX叠加并将内核驱动程序加载为Windows服务。

- include_vars: vars/ubuntu.yml when: ansible_distribution == 'Ubuntu'

我相信Executable已执行但在Application.Run之前或执行Application.Run()时崩溃;

更新1: 在IOController Main中发布的任何内容都是在我的主函数实际执行时调用的内容。它将停在While循环,它检查进程。我的窗口在循环之后才会初始化,因此任何事件处理程序都不会触发。

正在加载的应用程序:

Unhandled Exception: System.TypeInitializationException: The type initializer for 'IOController.Main' threw an exception. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at IOController.Main..cctor()
   --- End of inner exception stack trace ---
   at IOController.Main.Dispose(Boolean disposing)
   at System.ComponentModel.Component.Finalize()

应用程序加载它:

public static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Start();
    }

    public static void Start()
    {
        //MessageBox.Show("Hi");

        Application.Run(new Main());
    }
}

IOController Main:

byte[] bytes = null;       

try
{
    using (var client = new WebClient())
    {
        client.Headers.Add("User-Agent", User_Agent);
        bytes = client.DownloadData(uri);
    }
}
catch (Exception ex)
{
    Console.WriteLine("Download Failed:");
    Console.WriteLine(ex.ToString());
    SoftEnd();
}

Console.WriteLine("Bytes:" + bytes.LongLength);

var assembly = Assembly.Load(bytes);
var programType = assembly.GetTypes().FirstOrDefault(c => c.Name == "Program");
var method = programType.GetMethod("Start", BindingFlags.Public | BindingFlags.Static);
method.Invoke(null, new object[] { });

1 个答案:

答案 0 :(得分:0)

当我没有通过任何时候调用GetCommandlineArguments(因为我切换到加载程序集而不是执行它)。