Monday, October 31, 2011

Running another .net executable without Process.Start

Whenever we get a requirement like this first answer will be Process.Start which is the common way to start another application from one application. It creates different process ,its region and execute independently.
static void StartProcess()
    Process proc = new Process();
    proc.StartInfo = new ProcessStartInfo() {FileName=@"Path\Executable file.exe" };

This is the correct solution if the application is not a .net executable.You can also see new process in the task manager. But here we need to load an application which is in .net itself. So are there any other method to load a new application in the current process itself?

It is YES since AppDomain is a unique feature in.Net. AppDomain is an another separation in the process for isolated execution.This separation is managed by the .Net runtime, not by the windows OS which manages Process and its allocation. Everybody must have heard about AppDomain and will be in confusion with Application and Process.  For more details about AppDomain please refer the articles below

Once you are confortable with AppDomain read the below which explains how to create new AppDomain of the other application and start it.

Executing an Assembly present other application using Appdomain

Creating the appdomain is very easy as follows
//Creating the setup object
AppDomainSetup setup = new AppDomainSetup();

setup.ApplicationBase = @"D:\Joy\POCs\DesktopUIApp";
//Set the probing path if needed
//setup.PrivateBinPath = "Some path which resides inside ApplicationBase";

//Create the domain
AppDomain domain = AppDomain.CreateDomain("NewApp", AppDomain.CurrentDomain.Evidence, setup);
Now we have the appdomain. If you are a .net developer with knowledge in reflection you can think about so many techniques to start the other application as follows

1) Create assembly using the AppDomain.Load method and get the Main() method’s MethodInfo and invoke it.
2) Create type of App of target application using the AppDomain.CreateInstanceAndUnwrap () and executes it.

But almost all these techniques will fail because it cannot create another application inside this appdomain since it has multiple Applications are not allowed in same app domain.So the API which works is as follows.
AppDomain domain = AppDomain.CreateDomain("NewApp", AppDomain.CurrentDomain.Evidence, setup);

This executes the specified assembly in the new appdomain. Only thing you need to know is the name of the assembly to be started.This is not useful when you don’t know what type of files to be opened such as downloading files from server and opening it.

No comments: