none
How to MethodInfo.Invoke Main(string[] args) from an assembly? RRS feed

  • Question

  • I've the following code to load an assembly which has Main(string[] args). How can I invoke Main(string[] args) without args?

     

    Code Snippet

                    Assembly exeAssembly = Assembly.LoadFrom(exe);
                        object objToInvoke = exeAssembly.CreateInstance("NS.Class");
                        object s;
                        Type t = objToInvoke.GetType();
                        MethodInfo mi = t.GetMethod("Main",  BindingFlags.NonPublic | BindingFlags.Static);

                        s = mi.Invoke(objToInvoke, null);
                       

     

     

     

    Since mi.GetParameters().Length will return 1 for Main(string[] args), mi.Invoke(objToInvoke, null) caused "Parameter not matching" exception.

     

    However, if I set mi.Invoke(objToInvoke, new object[] { new string[] {""} });, this caused Main method assumed there is 1 argument whose value is "".

     

    Either way not working, please help.

     

    Thanks.


     

    Monday, February 18, 2008 11:41 AM

Answers

  • Hi,

     

    Try mi.Invoke(objToInvoke, new object[] { null });

    This will call Main method and pass null instead of array "string[] args".

    I think this is what you need.

     

    Monday, February 18, 2008 1:17 PM
  • Try this:

    s = mi.Invoke(objToInvoke, new string [] { });

    This creates an empty string arry just as you wanted.

    Yours,
      Alois Kraus

    Tuesday, February 19, 2008 10:32 PM

All replies

  • Hi,

     

    Try mi.Invoke(objToInvoke, new object[] { null });

    This will call Main method and pass null instead of array "string[] args".

    I think this is what you need.

     

    Monday, February 18, 2008 1:17 PM
  • Great, this works. Thanks.

     

    Tuesday, February 19, 2008 8:29 AM
  • Sorry Vitaliy, it actually not working but returned me "null reference" exception....

     

    If I modified your statement to  mi.Invoke(objToInvoke, new object[] { new string[] {null} });

     

    This also not working. this caused args.Length = 1 at Main(args).

     

    Please advise, thanks. 

     

    Tuesday, February 19, 2008 10:59 AM
  • To be exact, I got, "Object reference not set to an instance of an object.", NullReferenceException with your 1st suggestion.

    Thanks.

    Tuesday, February 19, 2008 11:03 AM
  • I believe NullReferenceException is caused by code within Main method. I think this code tries to access some elements from args collection using indexer.
    Tuesday, February 19, 2008 12:08 PM
  • How the assembly can prevent this Invoke?

     

    Thanks you

    Michael

     

     

    Tuesday, February 19, 2008 3:21 PM
  • Try this:

    s = mi.Invoke(objToInvoke, new string [] { });

    This creates an empty string arry just as you wanted.

    Yours,
      Alois Kraus

    Tuesday, February 19, 2008 10:32 PM