【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).*" /> </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