如何将附属程序集嵌入到 EXE 文件中

Posted

技术标签:

【中文标题】如何将附属程序集嵌入到 EXE 文件中【英文标题】:How to embed a satellite assembly into the EXE file 【发布时间】:2010-11-30 00:55:58 【问题描述】:

我遇到的问题是我需要将 C# 项目作为单个 EXE 文件分发,该文件不是安装程序,而是真正的程序。它还需要包含当前位于子目录中的翻译。

是否可以直接嵌入到二进制文件中?

【问题讨论】:

【参考方案1】:

简短的回答是肯定的,有一个名为Assembly Linker (AL.exe) 的程序将以这种方式嵌入程序集。它的主要用例是本地化,听起来你也需要它。如果是这样,它应该是直截了当的。

例如:

al /t:lib /embed:strings.de.resources /culture:de /out:MyApp.resources.dll

al.exe /culture:en-US /out:bin\Debug\en-US\HelloWorld.resources.dll /embed:Resources\MyResources.en-US.resources,HelloWorld.Resources.MyResources.en-US .resources /template:bin\Debug\HelloWorld.exe

This 是 MSDN 的一个示例演练,其中包含上述示例等。此外,您可能还想阅读this blog post,它进一步解释了它的用法。

【讨论】:

博客文章的链接已损坏。 据我所知,al.exe 可以用来创建附属程序集,但我不认为它可以将多个文化资源合并到一个程序集中,这就是问题所要求的.【参考方案2】:

另一种选择是将其他程序集嵌入为 EmbededResource。然后处理应用程序域 AssemblyResolve,从这里您可以从资源中读取程序集并将其加载到运行时。类似于以下内容:

public class HookResolver

    Dictionary<string, Assembly> _loaded;

    public HookResolver()
    
        _loaded = new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    

    System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    
        string name = args.Name.Split(',')[0];
        Assembly asm;
        lock (_loaded)
        
            if (!_loaded.TryGetValue(name, out asm))
            
                using (Stream io = this.GetType().Assembly.GetManifestResourceStream(name))
                
                    byte[] bytes = new BinaryReader(io).ReadBytes((int)io.Length);
                    asm = Assembly.Load(bytes);
                    _loaded.Add(name, asm);
                
            
        
        return asm;
    

【讨论】:

【参考方案3】:

ILMerge 将为您的应用程序创建一个 exe 文件。你可以从微软download it。它将程序集合并在一起并可以将它们内部化,以便将合并的类设置为内部。这就是我多次用来创建单个文件版本的方法。集成到您的构建过程中非常容易。

【讨论】:

【参考方案4】:

这是我在网上看到的最简单的解决方案:

How to embed your application’s dependent DLLs inside your EXE file

这个解决方案也很方便的实现: http://code.google.com/p/costura/wiki/HowItWorksEmbedTask

【讨论】:

此链接现已失效。 @pjc50 更新了网络存档链接

以上是关于如何将附属程序集嵌入到 EXE 文件中的主要内容,如果未能解决你的问题,请参考以下文章

如何防止引用程序集的嵌入式依赖项被复制到Visual Studio中的输出文件夹?

如何在单个EXE中嵌入多语言* .resx(或* .resources)文件?

如何在 VS 创建的 exe 中嵌入引用?

AjaxControlToolkit.Properties.Resources.NET4.resources正确嵌入或链接到程序集“

C# - 无法从 ResourceManager 获取字符串(来自附属程序集)

ef核心 - 如何将类映射的多个变体放到同一个表中