Embedding DLL's into .exe in in Visual C# 2010

前端 未结 8 2293
臣服心动
臣服心动 2020-12-14 10:31

I\'m working on a C# program that uses iTextSharp.dll and WebCam_Capture.dll. When I build the program, it creates executable in the debug folder and it also copies these tw

相关标签:
8条回答
  • 2020-12-14 11:20

    Check out the AssemblyResolve event on the app domain.

    I don't have a sample but you basically check what is asked for and stream back the resource DLL. I believe LinqPAD does this well - you could have a look at Joseph Albahari's implementation with a decompiler etc.

    0 讨论(0)
  • 2020-12-14 11:21
    1. Add the DLL files to your Visual Studio project.
    2. For each file go to "Properties" and set its Build Action to "Embedded Resource"
    3. On your code retrive the resource using the GetManifestResourceStream("DLL_Name_Here") this returns a stream that can be loadable.
    4. Write an "AssemblyResolve" event handler to load it.

    Here is the code:

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.IO;
    
    namespace WindowsForm
    {
        public partial class Form1 : Form
        {
            Dictionary<string, Assembly> _libs = new Dictionary<string, Assembly>();            
    
            public Form1()
            {
                InitializeComponent();
                AppDomain.CurrentDomain.AssemblyResolve += FindDLL;
            }
    
            private Assembly FindDLL(object sender, ResolveEventArgs args)
            {
                string keyName = new AssemblyName(args.Name).Name;
    
                // If DLL is loaded then don't load it again just return
                if (_libs.ContainsKey(keyName)) return _libs[keyName];
    
    
                using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespaceGoesHere." + keyName + ".dll"))  // <-- To find out the Namespace name go to Your Project >> Properties >> Application >> Default namespace
                {
                    byte[] buffer = new BinaryReader(stream).ReadBytes((int)stream.Length);
                    Assembly assembly = Assembly.Load(buffer);
                    _libs[keyName] = assembly;
                    return assembly;
                }
            }
    
            //
            // Your Methods here
            //
    
        }
    }
    

    Hope it helps, Pablo

    0 讨论(0)
提交回复
热议问题