embed an executable (or any other file) into your application in C# (转载)
Sometimes it is necessary to embed an executable (or any other file) into your application
and later recreate it during runtime. At the center of the technique are the Resource capabilities
of .NET and the concept of Reflection. Below is an example of such a technique using C#.
Steps in 'plain' English
1. Embed executables using Visual Studio IDE.
2. Use Reflection to investigate current assembly for all embedded resources.
3. For desired Resource(s), open a Stream to the Resource.
4. Read from this Stream and simultaneously write the contents of Stream to disk.
|
Sample Source Code
//====================================================== //Recreate all executable resources //====================================================== private void mRecreateAllExecutableResources() { // Get Current Assembly refrence Assembly currentAssembly = Assembly.GetExecutingAssembly(); // Get all imbedded resources string[] arrResources = currentAssembly.GetManifestResourceNames();
foreach (string resourceName in arrResources) { if (resourceName.EndsWith(".exe")) { //or other extension desired //Name of the file saved on disk string saveAsName = resourceName; FileInfo fileInfoOutputFile = new FileInfo(saveAsName); //CHECK IF FILE EXISTS AND DO SOMETHING DEPENDING ON YOUR NEEDS if (fileInfoOutputFile.Exists) { //overwrite if desired (depending on your needs) //fileInfoOutputFile.Delete(); } //OPEN NEWLY CREATING FILE FOR WRITTING FileStream streamToOutputFile = fileInfoOutputFile.OpenWrite(); //GET THE STREAM TO THE RESOURCES Stream streamToResourceFile = currentAssembly.GetManifestResourceStream(resourceName);
//--------------------------------- //SAVE TO DISK OPERATION //--------------------------------- const int size = 4096; byte[] bytes = new byte[4096]; int numBytes; while ((numBytes = streamToResourceFile.Read(bytes, 0, size)) > 0) { streamToOutputFile.Write(bytes, 0, numBytes); }
streamToOutputFile.Close(); streamToResourceFile.Close(); }//end_if
}//end_foreach }//end_mRecreateAllExecutableResources | |
Each individual file must be added into your solution as an Embedded Resource? To do this right
click in the Solution Explorer then select: Add-> Existing Item. Now locate the executable (or any other)
file of your choice and then select it. You will now see this file in the Solution Explorer. Now right
click on it and choose Properties-> Make sure "Build Action" has "Embedded Resource" selected.
![](https://images.cnblogs.com/cnblogs_com/wuhenke/add_existing.jpg)
![](https://images.cnblogs.com/cnblogs_com/wuhenke/add_existing_properties.jpg)
|
另外资源:
http://devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=75