wpf中将引用的dll文件打包到exe中
业务场景:在做一个打包程序中,需要引用到一个ICSharpCode.SharpZipLib.dll的第三方库,编译之后dll需要生成到目录里面exe才能使用,但是只想给用户发送一个纯exe的安装文件,不想有关联的引用,怎么办呢?提供一种方法:
1、将dll文件以资源的方式包含到项目中,再进行引用
2、在程序入口添加程序集解析事件(wpf的App.xaml.cs文件)
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); //添加程序集解析事件 AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly; } private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); var executingAssemblyName = executingAssembly.GetName(); var resName = executingAssemblyName.Name + ".resources"; AssemblyName assemblyName = new AssemblyName(args.Name); string path = ""; if (resName == assemblyName.Name) { path = executingAssemblyName.Name + ".g.resources"; ; } else { path = assemblyName.Name + ".dll"; if (assemblyName.CultureInfo != null && assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false) { path = String.Format(@"{0}\{1}", assemblyName.CultureInfo, path); } } using (Stream stream = executingAssembly.GetManifestResourceStream(path)) { if (stream == null) return null; byte[] assemblyRawBytes = new byte[stream.Length]; stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length); return Assembly.Load(assemblyRawBytes); } }
3、更改.csproj的项目文件
在Import节点后面添加如下代码
<Target Name="AfterResolveReferences"> <ItemGroup> <EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'"> <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName> </EmbeddedResource> </ItemGroup> </Target>
原理:就是将dll文件以资源的方式嵌入包含到项目中,编译后目录里面仍然会编译出dll,我们将dll删除,发现程序仍然能运行,这是因为我们在入口注册了程序集解析事件
当程序集解析引用异常或有相关错误时,会进入事件,在事件中我们将嵌入的dll文件以流的方式映射加载,就相当于重新加载了删除的dll文件
网上好像还有别的方法如引用第三方库Fody.Costura(未测)