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

相关推荐
I'mSQL12 小时前
WPF资源字典合并报错
wpf
one99617 小时前
WPF应用程序中的异常处理
c#·.net·wpf
somethingGoWay2 天前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay2 天前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
self_myth3 天前
[特殊字符] 深入理解操作系统核心特性:从并发到分布式,从单核到多核的全面解析
windows·macos·wpf·harmonyos
c#上位机3 天前
wpf之TextBlock
c#·wpf
玉面小君4 天前
从 WPF 到 Avalonia 的迁移系列实战篇6:ControlTheme 和 Style区别
c#·wpf·avalonia
c#上位机4 天前
wpf之Border
c#·wpf
SunflowerCoder4 天前
WPF迁移avalonia之图像处理(一)
图像处理·wpf·avalonia
周杰伦fans4 天前
WPF中的DataContext以及常见的绑定方式
wpf