.net framework wpf 打包免安装exe文件

1、打开所在项目csproj文件添加以下内容:

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

2、App.xmal.cs类添加以下代码

cs 复制代码
 public partial class App : Application
 {
     public App()
     {
         AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
     }

     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);
     }
 }

3、打包删除exe以外的文件,需要在所在项目csproj文件添加以下内容

cs 复制代码
<Target Name="DeleteOtherFile" AfterTargets="AfterBuild">
        <ItemGroup>
            <OtherFiles Include="$(OutputPath)\*" Exclude="$(OutputPath)\$(AssemblyName).exe" />
        </ItemGroup>
        <Delete Files="@(OtherFiles)" />
    </Target>
相关推荐
唐青枫8 分钟前
别滥用 Task.Run:C# 异步并发实操指南
c#·.net
✎ ﹏梦醒͜ღ҉繁华落℘13 小时前
开发WPF项目时遇到的问题总结
wpf
zzzhpzhpzzz14 小时前
Win10快速安装.NET3.5
.net·win10
许泽宇的技术分享16 小时前
Windows MCP.Net:基于.NET的Windows桌面自动化MCP服务器深度解析
windows·自动化·.net
百锦再1 天前
.NET 的 WebApi 项目必要可配置项都有哪些?
java·开发语言·c#·.net·core·net
hqwest1 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
Vae_Mars2 天前
WPF中使用InputBindings进行快捷键绑定
wpf
做一位快乐的码农2 天前
基于.net、C#、asp.net、vs的保护大自然网站的设计与实现
c#·asp.net·.net
hqwest2 天前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
YF云飞2 天前
.NET 在鸿蒙系统(HarmonyOS Next)上的适配探索与实践
华为·.net·harmonyos