.net framework wpf 打包免安装exe文件
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、App.xmal.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文件添加以下内容
<Target Name="DeleteOtherFile" AfterTargets="AfterBuild">
<ItemGroup>
<OtherFiles Include="$(OutputPath)\*" Exclude="$(OutputPath)\$(AssemblyName).exe" />
</ItemGroup>
<Delete Files="@(OtherFiles)" />
</Target>