Monday, May 5, 2008

How to load an application and run from memory using C#?

This shows how to load an application and run from memory system. After the application load, you can use it without the source EXE file (usually blocked from the system) Useful when you don't have to have the source EXE file on HDD (E.g. on a USB key)

First Step

Load the exe file in one stream and read it as an array of bytes:

// read the bytes from the application exe file
FileStream fs = new FileStream(filePath, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
fs.Close();
br.Close();

Using the FileStream class is possible to open the exe file (location indicated in the filePath variable), read and close it to release resources.

Second Step

Use the Assembly.Load method to load the exe file (as array of bytes) into the Assembly cache:

// load the bytes into Assembly
Assembly a = Assembly.Load(bin);

Now we can try to find the Entry Point of the application:

// search for the Entry Point
MethodInfo method = a.EntryPoint;
if (method != null) { ... }

If an Entry Point is found, is possible to create an Istance of the Application Main method and invoke it from our application launcher:

// create an istance of the Startup form Main method
object o = a.CreateInstance(method.Name);

// invoke the application starting point
method.Invoke(o, null);

If all will be ok, the called application will start without using the source EXE file (try to move it to check).

NOTE: Pay attention to the Application.SetCompatibleTextRenderingDefault method of the called application. Visual Studio 2005 applies this line in the Main method (located inside the Program.cs file) to use the new GDI+ library in our applications, but it will throw an exception because it must be called before the first IWin32Window object is created.