views:

2117

answers:

4

How do I embed an external executable inside my C# Windows Forms application?

Edit: I need to embed it because it's an external free console application (made in C++) from which I read the output values to use in my program. It would be nice and more professional to have it embedded.

Second reason is a requirement to embed a Flash projector file inside a .NET application.

+3  A: 

Is the executable a managed assembly? If so you can use ILMerge to merge that assembly with yours.

Andrew Hare
+3  A: 

Just add it to your project and set the build option to "Embedded Resource"

scottm
+1  A: 

Here is some sample code that would roughly accomplish this, minus error checking of any sort. Also, please make sure that the license of the program to be embedded allows this sort of use.

// extracts [resource] into the the file specified by [path]
void ExtractResource( string resource, string path )
{
    Stream stream = GetType().Assembly.GetManifestResourceStream( resource );
    byte[] bytes = new byte[(int)stream.Length];
    stream.Read( bytes, 0, bytes.Length );
    File.WriteAllBytes( path, bytes );
}

string exePath = "c:\temp\embedded.exe";
ExtractResource( "myProj.embedded.exe", exePath );
// run the exe...
File.Delete( exePath );

The only tricky part is getting the right value for the first argument to ExtractResource. It should have the form "namespace.name", where namespace is the default namespace for your project (find this under Project | Properties | Application | Default namespace). The second part is the name of the file, which you'll need to include in your project (make sure to set the build option to "Embedded Resource"). If you put the file under a directory, e.g. Resources, then that name becomes part of the resource name (e.g. "myProj.Resources.Embedded.exe"). If you're having trouble, try opening your compiled binary in Reflector and look in the Resources folder. The names listed here are the names that you would pass to GetManifestResourceStream.

Charlie
GETMANIFESTRESOURCESTREAM! SLOWLY I TURNED... STEP BY STEP... INCH BY INCH...
Will
Ahem. GMRS is the OLD way to do this. You can just embed the .exe in the assembly as a byte array which is accessible as a property. Two steps to get it and save it to disk, instead of the monstrosity with magic strings you've suggested. [Here's a page on how to create strongly typed resources in VS.](http://msdn.microsoft.com/en-us/library/t69a74ty(VS.90).aspx)
Will
Sorry, clearly this isn't the most up-to-date answer, but I'm not sure it really deserves to be called a "monstrosity".
Charlie
A: 

What is the better method? The link is not opening.

Aditi