Tuesday, January 22, 2019

[C#] Embed referenced assemblies into execurtable




namespace Vurdalakov
{
    using System;
    using System.Reflection;
    using System.Windows.Forms;

    static class Program
    {
        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.AssemblyResolve += OnAppDomainAssemblyResolve;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }

        private static Assembly OnAppDomainAssemblyResolve(Object sender, ResolveEventArgs args)
        {
            var resourceName = "Vurdalakov.Reflection." + new AssemblyName(args.Name).Name + ".dll";

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                if (stream != null)
                {
                    var assemblyData = new Byte[stream.Length];
                    stream.Read(assemblyData, 0, assemblyData.Length);
                    return Assembly.Load(assemblyData);
                }
            }

            return null;
        }
    }
}

No comments:

Post a Comment