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 thr开发者_如何学JAVAows this exception since on this line:
object o = assembly.CreateInstance(method.Name);
o
is remaining 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.)
What am i doing wrong?
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]);
If the entry point method is not public, you should use the Invoke overload that allows you to specify BindingFlags
.
if you check any WinForm application Program.cs file you'll see there always these 2 lines
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?
精彩评论