How to embed exe or resource file in c# assembly

Sometimes it is necessary to embed an executable (or any other file) into your application and later recreate it during runtime.In this post I will show you how to embed resource in assembly (application)

  • Open visual studio and create a new console application 
  • Right click on the project and add existing file (resource)




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.





C# Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace Embed_Resource
{
    class Program
    {
        /// <summary>
        /// This function read the name of all resouce file names from the assembly,and print those name on consolse
        /// </summary>
        private static void ReadResourceNameFromAssembly()
        {
            foreach (var resouceName in Assembly.GetExecutingAssembly().GetManifestResourceNames())
            {
                Console.WriteLine(resouceName);
            }
        }
        private static void RetriveResourceFromAssembly()
        {
            string resouceName = "Embed_Resource.data.txt";
            //Get current executing assembly
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            //Get All resources from assembly
            //Create stream for output file
            FileStream outputFileStream=new FileStream(@"D:\output.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite);
            //Get stream to the resouce
            Stream resouceStream = currentAssembly.GetManifestResourceStream(resouceName);
            //copy resoucestream to outputstram
            if (resouceStream != null)
            {
                resouceStream.CopyTo(outputFileStream);
                resouceStream.Close();
            }
            outputFileStream.Close();
        }
        static void Main(string[] args)
        {
            RetriveResourceFromAssembly();
        }
    }
}

No comments:

Post a Comment