gpt4 book ai didi

c# - 在 Visual C# 2010 中将 DLL 嵌入到 .exe 中

转载 作者:可可西里 更新时间:2023-11-01 07:54:11 28 4
gpt4 key购买 nike

我正在开发一个使用 iTextSharp.dll 和 WebCam_Capture.dll 的 C# 程序。当我构建程序时,它会在调试文件夹中创建可执行文件,并且还会按预期将这两个 dll 复制到调试文件夹。我想将它们合并成一个可执行文件,但是我失败了。这两个库通常在解决方案资源管理器中的引用中可见。我还将它们添加为资源。可执行文件的大小变大了,等于三个文件的总和,但是可执行文件的目录中仍然需要这些库……我玩了资源文件的“构建操作”属性,但没有改变。我也试过 ILmerge 但它给了我一个错误。那我该怎么办呢?

更新:这是我从 ILmerge 得到的:

An exception occurred during merging:
Unresolved assembly reference not allowed: System.Core.
at System.Compiler.Ir2md.GetAssemblyRefIndex(AssemblyNode assembly)
at System.Compiler.Ir2md.GetTypeRefIndex(TypeNode type)

顺便说一下,它只是一个 Windows 应用程序,一个可以填写并打印为 pdf 的表格,如果可用的话,还可以通过网络摄像头拍摄照片。谢谢大家!

最佳答案

您可以使用 ILMerge将多个程序集合并在一起。你已经说过你这样做了,但你收到了一个错误。虽然我不知道为什么,但您可以使用替代方法:如果库是开源的(并且它们的许可证与您的许可证兼容),您可以下载源代码,将其添加到您的项目中并编译。这将生成一个程序集。

ILMerge 页面还列出了 Jeffrey Richter's blog作为解决您问题的另一种选择:

Many applications consist of an EXE file that depends on many DLL files. When deploying this application, all the files must be deployed. However, there is a technique that you can use to deploy just a single EXE file. First, identify all the DLL files that your EXE file depends on that do not ship as part of the Microsoft .NET Framework itself. Then add these DLLs to your Visual Studio project. For each DLL file you add, display its properties and change its “Build Action” to “Embedded Resource.” This causes the C# compiler to embed the DLL file(s) into your EXE file, and you can deploy this one EXE file.

At runtime, the CLR won’t be able to find the dependent DLL assemblies, which is a problem. To fix this, when your application initializes, register a callback method with the AppDomain’s ResolveAssembly event. The code should look something like this:

AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { 
String resourceName = "AssemblyLoadingAndReflection." +
new AssemblyName(args.Name).Name + ".dll";
using (var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName)) {
Byte[] assemblyData = new Byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
};

Now, the first time a thread calls a method that references a type in a dependent DLL file, the AssemblyResolve event will be raised and the callback code shown above will find the embedded DLL resource desired and load it by calling an overload of Assembly’s Load method that takes a Byte[] as an argument.

关于c# - 在 Visual C# 2010 中将 DLL 嵌入到 .exe 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6920920/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com