Introduction
Suppose you are working on an application - which needs to extract another application at runtime. How do you do that?
We can start with the steps below:
Step 1. Create a new Console Application
Step 2. Embed an exe file inside it
For this - right click on the solution explorer window and choose "Add existing item"
In the appearing dialog box - type c:\windows\system32\regedt32.exe
For convenience, I am using the registry editor utility of windows.
(Note. if your windows folder is in a different drive you have to change the above path)
Now you can see the file added to solution explorer.
Choose the properties of the file and change the Build Action property to Embedded Resource.
Now build your project - if successful you are ready with an exe embedded.
Step 3. Get the embedded resource name
Now our goal is to save the embedded exe in runtime to the same application folder. For achieving this we have to first get the embedded name of the exe file.
The embedded name of the resource file would be in the format ApplicationNameSpace.ResourceName.
In our case, it is EmbedExe.regedt32.exe
You can use the method
Assembly.GetExecutingAssembly().GetManifestResourceNames()
to get all the resource names in the assembly.
Step 4. Save the embedded resource
In this final step, we are retrieving the bytes of assembly and save them into a file stream. For this we are using Stream, and FileStream classes.
The code is given below
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EmbedExe.regedt32.exe");
FileStream fileStream = new FileStream("new.exe", FileMode.CreateNew);
for (int i = 0; i < stream.Length; i++)
fileStream.WriteByte((byte)stream.ReadByte());
fileStream.Close();
We can see in the output folder that the new.exe is created.