整個程序依賴很多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