Eli Waxman
Eli Waxman

Reputation: 2897

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?

Upvotes: 6

Views: 11177

Answers (3)

Nicole Calinoiu
Nicole Calinoiu

Reputation: 20992

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.

Upvotes: 4

surfen
surfen

Reputation: 4692

How about calling it in it's own process?

Upvotes: 0

Eugen
Eugen

Reputation: 2990

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.

Upvotes: 1

Related Questions