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

前端 未结 8 2317
臣服心动
臣服心动 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:06

    I modified Pablo's code a little bit and it worked for me.
    It was not getting the DLL's resource name correctly.

    IDictionary _libs = new Dictionary();
    
    public Form1()
    {
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
        InitializeComponent();
    }
    
    // dll handler
    System.Reflection.Assembly CurrentDomain_AssemblyResolve(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(GetDllResourceName("itextsharp.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;
        }
    }
    
    private string GetDllResourceName(string dllName)
    {
        string resourceName = string.Empty;
        foreach (string name in Assembly.GetExecutingAssembly().GetManifestResourceNames())
        {
            if (name.EndsWith(dllName))
            {
                resourceName = name;
                break;
            }
        }
    
        return resourceName;
    }
    

提交回复
热议问题