WPF 将引入的dll嵌入至.exe中

在项目文件中添加

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

在app.xaml中添加

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

}

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
//删除dll
string exePath = AppDomain.CurrentDomain.BaseDirectory;
if(File.Exists(exePath+ "xxx.dll"))
{
File.Delete(exePath + "xxx.dll");
}
if(File.Exists(exePath+ "xxx.xml"))
{
File.Delete(exePath + "xxx.xml");
}
}

posted @ 2021-12-29 10:33  奇迹之耀  阅读(188)  评论(0编辑  收藏  举报