如何将程序集加载到内存中并执行它

这就是我在做的事情:

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 – 它发现该方法是main,但它抛出此exception,因为在这一行:

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

o保持为空。 所以我在堆栈跟踪中挖了一下,实际的错误是这样的:

InnerException = {“SetCompatibleTextRenderingDefault应该在程序中创建第一个IWin32Window对象之前被调用”}(这是我的翻译,因为它给了我一半希伯来语半英语的堆栈跟踪,因为我的窗口是希伯来语。)

我究竟做错了什么?

入口点方法是静态的,因此应使用“instance”参数的null值调用它。 尝试使用以下内容替换Assembly.Load行之后的所有内容:

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

如果入口点方法不是公共的,则应使用允许您指定BindingFlags的Invoke重载。

如果您检查任何WinForm应用程序Program.cs文件,您将看到总是这两行

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

你需要在你的集会中打电话给他们。 至少这是你的例外所说的。

如何在它自己的过程中调用它?