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内了;

相关推荐
The Sheep 20238 小时前
WPF自定义路由事件
大数据·hadoop·wpf
阳光雨滴8 小时前
使用wpf用户控件编程落石效果动画
c++·wpf
wuty0079 小时前
WPF 调用 ChangeWindowMessageFilterEx 修改指定窗口 (UIPI) 消息筛选器的用户界面特权隔离
wpf·sendmessage·changewindowmessagefilterex·uip·消息筛选器的用户界面特权隔离·window message
攻城狮CSU15 小时前
WPF中核心接口 INotifyPropertyChanged
wpf
c#上位机15 小时前
wpf之Interaction.Triggers
c#·wpf
是木子啦19 小时前
wpf passwordbox控件 光标移到最后
c#·wpf
The Sheep 202319 小时前
wpf 命令理解
wpf
布伦鸽19 小时前
C# WPF DataGrid使用Observable<Observable<object>类型作为数据源
开发语言·c#·wpf
分布式存储与RustFS1 天前
告别复杂配置:用Milvus、RustFS和Vibe Coding,60分钟DIY专属Chatbot
wpf·文件系统·milvus·对象存储·minio·rustfs·vibe
攻城狮CSU2 天前
WPF 绑定机制实现原理
wpf