是否可以将一个预先存在的DLL嵌入到一个编译好的c#可执行文件中(这样你就只有一个文件可以分发)?如果这是可能的,人们会怎么去做呢?

通常情况下,我不介意把dll放在外面,让安装程序处理所有事情,但工作中有几个人问过我这个问题,老实说,我不知道。


当前回答

如果你使用的是。net Core 3.0

你可以使用带有PublishSingleFile属性的dotnet publish命令:

dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true

唯一的缺点是你最终会得到一个巨大的EXE文件。

其他回答

我强烈推荐使用Costura。Fody -到目前为止在程序集中嵌入资源的最好和最简单的方法。它可以作为NuGet包使用。

Install-Package Costura.Fody

将其添加到项目后,它将自动将复制到输出目录的所有引用嵌入到主程序集中。你可能想要通过添加一个目标到你的项目来清除嵌入的文件:

Install-CleanReferencesTarget

您还可以指定是否包含pdb、排除某些程序集或动态提取程序集。据我所知,也支持非托管程序集。

更新

目前,一些人正在尝试添加对DNX的支持。

更新2

对于最新的Fody版本,您需要MSBuild 16(因此Visual Studio 2019)。Fody 4.2.1版本将支持MSBuild 15。(参考:Fody只支持MSBuild 16及以上版本。当前版本:15)

如果程序集只有托管代码,ILMerge可以将程序集组合为一个程序集。您可以使用命令行应用程序,或添加对exe的引用,并以编程方式合并。对于GUI版本,有Eazfuscator和。net z,这两个都是免费的。付费应用包括BoxedApp和SmartAssembly。

如果你必须将程序集与非托管代码合并,我建议使用SmartAssembly。我在使用SmartAssembly时从未遇到过问题,但在使用其他所有产品时都遇到过问题。在这里,它可以将所需的依赖项作为资源嵌入到主exe中。

你可以手动完成所有这些,不需要担心程序集是否被管理,或者通过将dll嵌入到资源中,然后依赖AppDomain的程序集ResolveHandler来混合模式。这是一种一站式解决方案,它采用了最坏的情况,即带有非托管代码的程序集。

static void Main()
{
    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
    {
        string assemblyName = new AssemblyName(args.Name).Name;
        if (assemblyName.EndsWith(".resources"))
            return null;

        string dllName = assemblyName + ".dll";
        string dllFullPath = Path.Combine(GetMyApplicationSpecificPath(), dllName);

        using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + ".Resources." + dllName))
        {
            byte[] data = new byte[stream.Length];
            s.Read(data, 0, data.Length);

            //or just byte[] data = new BinaryReader(s).ReadBytes((int)s.Length);

            File.WriteAllBytes(dllFullPath, data);
        }

        return Assembly.LoadFrom(dllFullPath);
    };
}

The key here is to write the bytes to a file and load from its location. To avoid chicken and egg problem, you have to ensure you declare the handler before accessing assembly and that you do not access the assembly members (or instantiate anything that has to deal with the assembly) inside the loading (assembly resolving) part. Also take care to ensure GetMyApplicationSpecificPath() is not any temp directory since temp files could be attempted to get erased by other programs or by yourself (not that it will get deleted while your program is accessing the dll, but at least its a nuisance. AppData is good location). Also note that you have to write the bytes each time, you cant load from location just 'cos the dll already resides there.

对于托管dll,您不需要写入字节,而是直接从dll的位置加载,或者只是读取字节并从内存加载程序集。像这样左右:

    using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + ".Resources." + dllName))
    {
        byte[] data = new byte[stream.Length];
        s.Read(data, 0, data.Length);
        return Assembly.Load(data);
    }

    //or just

    return Assembly.LoadFrom(dllFullPath); //if location is known.

如果程序集是完全非托管的,您可以查看此链接或此链接以了解如何加载此类dll。

通常,您需要某种形式的后构建工具来执行您所描述的程序集合并。有一个免费的工具叫做Eazfuscator (eazfuscator.blogspot.com/),它是为字节码分解设计的,同时也处理程序集合并。您可以将此添加到Visual Studio的构建后命令行中以合并程序集,但由于在任何重要的程序集合并场景中会出现的问题,您的里程将有所不同。

您还可以检查构建make untitil NANT是否具有在构建后合并程序集的功能,但我自己对NANT不够熟悉,无法确定是否内置了该功能。

还有很多很多Visual Studio插件会在构建应用程序时执行程序集合并。

或者,如果你不需要自动完成,有很多工具,比如ILMerge,可以将。net程序集合并到一个文件中。

我在合并程序集时遇到的最大问题是它们是否使用类似的名称空间。或者更糟的是,引用同一个dll的不同版本(我的问题通常是NUnit dll文件)。

ILMerge方法和Lars Holm Jensen处理AssemblyResolve事件都不适用于插件主机。例如,可执行文件H动态加载程序集P,并通过在单独的程序集中定义的接口IP访问它。要将IP嵌入到H one中,需要对Lars的代码进行一些修改:

Dictionary<string, Assembly> loaded = new Dictionary<string,Assembly>();
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{   Assembly resAssembly;
    string dllName = args.Name.Contains(",") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");
    dllName = dllName.Replace(".", "_");
    if ( !loaded.ContainsKey( dllName ) )
    {   if (dllName.EndsWith("_resources")) return null;
        System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
        byte[] bytes = (byte[])rm.GetObject(dllName);
        resAssembly = System.Reflection.Assembly.Load(bytes);
        loaded.Add(dllName, resAssembly);
    }
    else
    {   resAssembly = loaded[dllName];  }
    return resAssembly;
};  

处理重复尝试解析相同程序集并返回现有程序集而不是创建新实例的技巧。

编辑: 为了避免破坏. net的序列化,请确保所有没有嵌入到您的程序集中的程序集都返回null,从而默认使用标准行为。你可以通过以下方式获得这些库的列表:

static HashSet<string> IncludedAssemblies = new HashSet<string>();
string[] resources = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
for(int i = 0; i < resources.Length; i++)
{   IncludedAssemblies.Add(resources[i]);  }

如果传递的程序集不属于IncludedAssemblies,则返回null。

以下方法不使用外部工具,自动包含所有需要的DLL(不需要手动操作,一切都在编译时完成)

我在这里读了很多回答说使用ILMerge, ILRepack或Jeffrey Ritcher方法,但这些方法都不适合WPF应用程序,也不容易使用。

当你有很多DLL时,很难手动将你需要的DLL包含在你的exe中。我发现的最好的方法是由wegger在StackOverflow上解释的

为了清晰起见,Copy将他的答案粘贴在这里(全部归功于weged)


1)添加到你的。csproj文件:

<Target Name="AfterResolveReferences">
  <ItemGroup>
    <EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
      <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
    </EmbeddedResource>
  </ItemGroup>
</Target>

2)让你的Main Program.cs看起来像这样:

[STAThreadAttribute]
public static void Main()
{
    AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
    App.Main();
}

3)添加OnResolveAssembly方法:

private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
    Assembly executingAssembly = Assembly.GetExecutingAssembly();
    AssemblyName assemblyName = new AssemblyName(args.Name);

    var path = assemblyName.Name + ".dll";
    if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false) path = String.Format(@"{0}\{1}", assemblyName.CultureInfo, path);

    using (Stream stream = executingAssembly.GetManifestResourceStream(path))
    {
        if (stream == null) return null;

        var assemblyRawBytes = new byte[stream.Length];
        stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
        return Assembly.Load(assemblyRawBytes);
    }
}