I want to load another C# windows form application that I created with my current windows form application. I want to load it from memory. However, I am running into:
An unhandled exception of type ‘System.Reflection.TargetInvocationException’ occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an invocation.
private void button1_Click(object sender, EventArgs e)
{
FileStream _FileStream = new FileStream("load.exe", FileMode.Open);
BinaryReader _BinaryReader = new BinaryReader(_FileStream);
byte[] bBytes = _BinaryReader.ReadBytes(Convert.ToInt32(_FileStream.Length));
_BinaryReader.Close();
_FileStream.Close();
Assembly a = Assembly.Load(bBytes);
MethodInfo method = a.EntryPoint;
if (method != null)
{
object o = a.CreateInstance(method.Name);
method.Invoke(o,null);
}
}
Look at the exception’s InnerException property to know the actual exception that made the code bomb.
The code you used is definitely wrong but not actually the reason for the failure. Fwiw, the Main() entrypoint is a static method, you don’t create an instance of the Program class. method.Invoke(null, null) is the correct way.
But it isn’t going to work, you are obviously running this code in a Winforms app. The program you’re trying to load is also a Winforms app. And will try to use the one-and-only Application class object. That cannot work:
It may look like this will work when you try this from a console mode application. It actually doesn’t, the Main() method of a console app doesn’t have the [STAThread] attribute. A hard requirement for GUI apps. Without it, lots of typical GUI operations will fail in mysterious ways. Anything that uses the clipboard, drag and drop, the shell dialogs like OpenFileDialog for example requires an STA thread.
This just isn’t going to fly. Consider Process.Start().