How to embed exe or resource file in c# assembly

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

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

We must add each individual file 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();
        }
    }
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post