如何加载程序集到内存中,并执行它 [英] How to load assembly into memory and execute it
问题描述
这是即时通讯做什么:
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());
}
}
的问题是,它抛出了 TargetInvocationException
- 它发现,该方法是主要的,但它引发此异常,因为在这条线:
The problem is that it throws that TargetInvocationException
- it finds that the method is main, but it throws this exception since on this line:
object o = assembly.CreateInstance(method.Name);
0
的剩余空。所以我挖了一个有点成堆栈跟踪和实际的错误是这样的:
o
is remaining null. So I dug a bit into that stacktrace and the actual error is this:
的InnerException = {SetCompatibleTextRenderingDefault应创建firstfirst IWin32Window对象之前调用在节目}(这是我的翻译,因为它给了我一半希伯来语一半英文的堆栈跟踪,因为我的窗户是希伯来文。)
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.)
我究竟做错了什么?
推荐答案
入口点方法是静态的,所以应该使用空值调用在实例参数。尝试用以下您的Assembly.Load行后更换的所有内容:
The entry point method is static, so it should be invoked using a null value for the "instance" parameter. Try replacing everything after your Assembly.Load line with the following:
assembly.EntryPoint.Invoke(null, new object[0]);
如果入口点方法是不公开的,你应该使用Invoke重载允许您指定的BindingFlags
。
If the entry point method is not public, you should use the Invoke overload that allows you to specify BindingFlags
.
这篇关于如何加载程序集到内存中,并执行它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!