You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7 WPF应用如何将本地化资源文件嵌入主程序集?

问题:如何将指定本地化资源嵌入WPF主程序集而非生成附属程序集?

场景与问题

我在WPF项目中配置了多语言资源文件,.csproj初始配置如下:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net7.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWPF>true</UseWPF>
    <UICulture>en</UICulture>
  </PropertyGroup>

  <ItemGroup>
    <EmbeddedResource Include="locale.en.restext" />
    <EmbeddedResource Include="locale.es.restext" />
    <EmbeddedResource Include="locale.fr.restext" />
  </ItemGroup>

</Project>

通过ResourceManager.GetString(String, CultureInfo)调用资源时,资源回退机制基本正常,但默认UICulture(en)的终极回退功能失效——即使添加了特性:

[assembly:NeutralResourcesLanguage( "en" ) ]

从编译输出可以看到,locale.en.restext被编译为附属程序集(生成了en子目录):

PS > Get-ChildItem .\bin\Debug\net7.0-windows

    Directory: C:\Users\user\path\to\proj\bin\Debug\net7.0-windows

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----          2023-05-18    23:56                en
d----          2023-05-18    23:56                es
d----          2023-05-18    23:56                fr
-a---          2023-05-18    23:56            679 Proj.deps.json
-a---          2023-05-18    23:56           6144 Proj.dll
-a---          2023-05-18    23:56         154624 Proj.exe
-a---          2023-05-18    23:56          12888 Proj.pdb
-a---          2023-05-18    23:56            266 Proj.runtimeconfig.json

只有添加UltimateResourceFallbackLocation.Satellite特性后回退才正常:

[assembly:NeutralResourcesLanguage( "en", UltimateResourceFallbackLocation.Satellite )]

但我需要将en对应的资源嵌入主程序集,而非生成附属程序集,该如何修改.csproj配置?

解决方案

修改.csproj中的EmbeddedResource配置,将作为中性语言的locale.en.restext指定为嵌入主程序集的资源,具体做法是给该资源项添加<LogicalName>,移除文件名中的文化标识,让编译器将其视为中性资源:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net7.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWPF>true</UseWPF>
    <UICulture>en</UICulture>
  </PropertyGroup>

  <ItemGroup>
    <!-- 将en资源设置为中性资源,嵌入主程序集 -->
    <EmbeddedResource Include="locale.en.restext">
      <LogicalName>locale.restext</LogicalName>
    </EmbeddedResource>
    <!-- 其他语言资源仍生成附属程序集 -->
    <EmbeddedResource Include="locale.es.restext" />
    <EmbeddedResource Include="locale.fr.restext" />
  </ItemGroup>

</Project>

配置后,locale.en.restext会被嵌入主程序集,不再生成en子目录的附属程序集。此时[assembly:NeutralResourcesLanguage( "en" )]特性就能正常触发终极回退逻辑,无需指定Satellite位置。

内容的提问来源于stack exchange,提问作者Leo Orientis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:05:24