WPF将dll文件嵌入到exe文件中

WPF将dll文件嵌入到exe文件中

第一步:打开.csproj文件,在Import节点后添加如下代码:

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

第二步:在App.xaml.cs文件中添加如下代码:

csharp 复制代码
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文件就嵌入exe内了;

相关推荐
林子漾17 小时前
【paper】分布式无人水下航行器围捕智能目标
分布式·wpf
wyh要好好学习1 天前
C# WPF 记录DataGrid的表头顺序,下次打开界面时应用到表格中
开发语言·c#·wpf
lgcgkCQ2 天前
任务调度中心-XXL-JOB使用详解
java·wpf·定时任务·任务调度
Vicky&James2 天前
英雄联盟客户端项目:从跨平台Uno Platform到Win UI3的转换只需要30分钟
github·wpf·跨平台·英雄联盟·winui·unoplatform
就是有点傻2 天前
WPF中如何使用区域导航
wpf
她说彩礼65万2 天前
WPF程序设置单例启动(互斥体)
wpf
就是有点傻2 天前
WPF中Prism框架中 IContainerExtension 和 IRegionManager的作用
wpf
月落.2 天前
WPF中MVVM工具包 CommunityToolkit.Mvvm
wpf·mvvm
月落.2 天前
WPF Prism框架
wpf·prism
Crazy Struggle3 天前
.NET 8.0 通用管理平台,支持模块化、WinForms 和 WPF
vue·wpf·winform·.net 8.0·通用权限管理