Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 394
Eli Braginskiy Avatar asked Apr 29 '11 22:04

Eli Braginskiy


People also ask

What is the method to load assembly given its file name and its path?

LoadFrom(String) Loads an assembly given its file name or path.

What is method to load assembly by name?

Loads an assembly given its AssemblyName. The assembly is loaded into the domain of the caller using the supplied evidence. Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly is loaded into the application domain of the caller.


2 Answers

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.

like image 83
Nicole Calinoiu Avatar answered Oct 26 '22 06:10

Nicole Calinoiu


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.

like image 24
Eugen Avatar answered Oct 26 '22 06:10

Eugen