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

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

    The answer you are looking for:

    // To embed a dll in a compiled exe:
    // 1 - Change the properties of the dll in References so that Copy Local=false
    // 2 - Add the dll file to the project as an additional file not just a reference
    // 3 - Change the properties of the file so that Build Action=Embedded Resource
    // 4 - Paste this code before Application.Run in the main exe
    AppDomain.CurrentDomain.AssemblyResolve += (Object sender, ResolveEventArgs args) =>
        {
            String thisExe = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            System.Reflection.AssemblyName embeddedAssembly = new System.Reflection.AssemblyName(args.Name);
            String resourceName = thisExe + "." + embeddedAssembly.Name + ".dll";
    
            using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                Byte[] assemblyData = new Byte[stream.Length];
                stream.Read(assemblyData, 0, assemblyData.Length);
                return System.Reflection.Assembly.Load(assemblyData);
            }
        };
    

提交回复
热议问题