How to load an assembly into memory and execute it

This is what I do:

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 this TargetInvocationException - it detects that the method is the main one, but it throws this exception, because in this line:

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

o remains equal to zero. So I dug a little into this stack, and the actual error is this:

InnerException = {"SetCompatibleTextRenderingDefault must be called before the first IWin32Window object is created in the program"} (this is my translation, since it gives me a stack of half Hebrew half English, since my windows are in Hebrew.)

What am I doing wrong?

+4
source share
3 answers

The entry point method is static, so it should be called using the zero value for the instance parameter. Try replacing everything after assembling Assembly.Load as follows:

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

If the entry point method is not public, you should use the Invoke overload, which allows you to specify BindingFlags .

+3
source

if you check any program file Program.cs WinForm, you will see that always these two lines

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

You need to also call the assembly. At least that's what your exception says.

+1
source

How about calling it in your own process ?

0
source

All Articles