简体   繁体   English

如何将程序集加载到 memory 并执行它

[英]How to load assembly into memory and execute it

This is what im doing:这就是我正在做的事情:

byte[] bytes = File.ReadAllBytes(@Application.StartupPath+"/UpdateMainProgaramApp.exe");
Assembly assembly = Assembly.Load(bytes);
// load the assemly

//Assembly assembly = Assembly.LoadFrom(AssemblyName);

// Walk through each type in the assembly looking for our class
MethodInfo method = assembly.EntryPoint;
if (method != null)
{
    // create an istance of the Startup form Main method
    object o = assembly.CreateInstance(method.Name);
    // invoke the application starting point
    try
    {
        method.Invoke(o, null);
    }
    catch (TargetInvocationException e)
    {
        Console.WriteLine(e.ToString());
    }
}

The problem is that it throws that TargetInvocationException - it finds that the method is main, but it throws this exception since on this line:问题是它抛出了TargetInvocationException - 它发现该方法是主要的,但它抛出了这个异常,因为在这一行:

object o = assembly.CreateInstance(method.Name);

o is remaining null. o是剩余的 null。 So I dug a bit into that stacktrace and the actual error is this:因此,我对该堆栈跟踪进行了一些研究,实际错误是:

InnerException = {"SetCompatibleTextRenderingDefault should be called before creating firstfirst IWin32Window object in the program"} (this is my translation since it gives me the stacktrace in half hebrew half english since my windows is in hebrew.) InnerException = {“SetCompatibleTextRenderingDefault 应该在程序中创建 firstfirst IWin32Window object 之前调用”}(这是我的翻译,因为它给了我一半希伯来语一半英语的堆栈跟踪,因为我的 windows 是希伯来语。)

What am i doing wrong?我究竟做错了什么?

The entry point method is static, so it should be invoked using a null value for the "instance" parameter.入口点方法是 static,因此应该使用“instance”参数的 null 值来调用它。 Try replacing everything after your Assembly.Load line with the following:尝试使用以下内容替换您的 Assembly.Load 行之后的所有内容:

assembly.EntryPoint.Invoke(null, new object[0]);

If the entry point method is not public, you should use the Invoke overload that allows you to specify BindingFlags .如果入口点方法不是公共的,您应该使用允许您指定BindingFlags的 Invoke 重载。

if you check any WinForm application Program.cs file you'll see there always these 2 lines如果您检查任何 WinForm 应用程序 Program.cs 文件,您将始终看到这两行

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

you need to call as well them in your assembly.您还需要在程序集中调用它们。 At least this is what your exception says.至少这是你的例外所说的。

How about calling it in it's own process ?在它自己的过程中调用它怎么样?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM