Neil Weicher
Neil Weicher

Reputation: 2502

C# Call Method in EXE

I have two C# DotNet executables: PARENT.EXE and CHILD.EXE. Built with Visual Studio 2010.

I want to load and call a method in CHILD.EXE from PARENT.EXE. So far I have been able to load CHILD.EXE as an Assembly using Assembly.LoadFrom. However, I am not clear on how to call the method in CHILD.EXE.

CHILD.EXE class looks like this:

namespace childnamespace;
public class childclass;
public string childmethod()
{
  return "hello world";
}

I want to call childmethod() from PARENT.EXE and get back the string "hello world".

I see lots of articles about how to load an EXE as an assembly, but not how to actually invoke a method in that assembly.


Additional information: thank to @MJ's reply I have the following code in PARENT.EXE

using System;
using System.Reflection;
using System.Diagnostics;
public static class ConsoleTest
{
    public static void Main()
    {
        Assembly SampleAssembly;
        try
        {
            SampleAssembly = Assembly.LoadFrom("child.exe");
            MethodInfo Method = 
              SampleAssembly.GetType("childnamespace.childclass").GetMethod("childmethod");
            if (Method != null)
            {
                Method.Invoke(null, null);  // exception here
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }
}

However I am getting the following exception at the indicated line:

Exception has been thrown by the target of an invocation.

Inner Exception:

Value cannot be null.

Upvotes: 0

Views: 3345

Answers (1)

MJ-
MJ-

Reputation: 64

Make childmethod a static method.

.GetType("childnamespace.childclass").GetMethod("childmethod").Invoke(null, null);

Upvotes: 2

Related Questions