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

相关推荐
xcLeigh1 天前
WPF进阶 | WPF 数据绑定进阶:绑定模式、转换器与验证
c#·wpf
学与用3 天前
【deepseek实战】绿色好用,不断网
ai·c#·wpf
的不对不4 天前
WPF基础03——InitializeComponent()函数解释
windows·c#·.net·wpf
军训猫猫头5 天前
61.异步编程1 C#例子 WPF例子
开发语言·c#·wpf
时光追逐者5 天前
一组开源、免费、Metro风格的 WPF UI 控件库
ui·开源·c#·.net·wpf·.netcore·微软技术
军训猫猫头5 天前
58.界面参数传递给Command C#例子 WPF例子
开发语言·ui·c#·wpf
xcLeigh6 天前
WPF基础 | 深入 WPF 事件机制:路由事件与自定义事件处理
c#·wpf
军训猫猫头7 天前
60.await与sleep的原理分析 C#例子 WPF例子
开发语言·ui·c#·wpf
敲代码的TKP8 天前
WPF自定义布局--瀑布布局
wpf
xcLeigh9 天前
WPF基础 | WPF 基础概念全解析:布局、控件与事件
c#·wpf