zoukankan      html  css  js  c++  java
  • 【Winform】所有的dll都打包到一个exe里

    整个程序依赖很多dll

    编译之后,Debug目录下会存在各种dll,比较乱。 

    想要的效果是,最后只有一个exe,发给别人也方便

    下面直接说方法

    1、修改 csproj 文件,在 </Project> 节点上面,添加下面的节点

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

    <Target Name="DeleteOtherFile" AfterTargets="AfterBuild"> <ItemGroup> <OtherFiles Include="$(OutputPath)\*" Exclude="$(OutputPath)\$(AssemblyName).exe" /> </ItemGroup> <Delete Files="@(OtherFiles)" /> </Target>

     2、修改Program方法,反射加载资源

    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp6
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
    
            private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
            {
                var executingAssembly = Assembly.GetExecutingAssembly();
                var assemblyName = new AssemblyName(args.Name);
    
                var path = assemblyName.Name + ".dll";
                if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false)
                    path = $@"{assemblyName.CultureInfo}\{path}";
    
                using (var 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);
                }
            }
        }
    }

    编译一下看看效果,已经只剩下一个大小几M的exe文件了,快乐的发给别人就好了。

    参考文档:https://www.jianshu.com/p/f9942d3a9270 

    每天进步一丢丢
    防盗签名:本文来自【博客园】-【多安分】

    恭喜兄dei,看到这个隐藏标签~~~如果觉得博客内容有所帮助,请扫二维码打赏,感谢老铁

    支付宝

    微信

  • 相关阅读:
    寒假学习5流程控制之ifelse与for循环
    寒假学习4scala数据类型与运算符
    寒假学习13
    寒假学习14
    寒假学习3scala简介与基础1
    sqlserver 定时自动备份
    windows mysql 主从同步
    mysql 连接数 最大并发数
    mysql基础语法
    sqlserver 常见语法
  • 原文地址:https://www.cnblogs.com/jhli/p/15529421.html
Copyright © 2011-2022 走看看