更新程序内嵌资源文件 (#6101)

* fix

* fix

* 移除自述

* 改用单例模式,避免多次初始化。

* 小修正

* 修正

* 更正自述

* 应该完成了

* 内嵌资源

* Update LocalizationHelper.cs
pull/6126/head
Slnanx 2024-11-18 09:57:38 +08:00 committed by GitHub
parent 10513e0f3b
commit 1866a59d12
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 25 additions and 21 deletions

View File

@ -1,11 +1,12 @@
using System.Globalization; using System.Globalization;
using System.Reflection;
using System.Text.Json; using System.Text.Json;
namespace AmazTool namespace AmazTool
{ {
public class LocalizationHelper public class LocalizationHelper
{ {
private static Dictionary<string, string> languageResources = new(); private static Dictionary<string, string> languageResources = [];
static LocalizationHelper() static LocalizationHelper()
{ {
@ -13,9 +14,6 @@ namespace AmazTool
LoadLanguageResources(); LoadLanguageResources();
} }
/// <summary>
/// 加载外部 JSON 文件中的语言资源
/// </summary>
private static void LoadLanguageResources() private static void LoadLanguageResources()
{ {
try try
@ -26,33 +24,39 @@ namespace AmazTool
currentLanguage = "en-US"; currentLanguage = "en-US";
} }
string jsonFilePath = $"{currentLanguage}.json"; string resourceName = $"AmazTool.{currentLanguage}.json";
if (!File.Exists(jsonFilePath)) var assembly = Assembly.GetExecutingAssembly();
{
jsonFilePath = "en-US.json";
}
var json = File.ReadAllText(jsonFilePath); using Stream? stream = assembly.GetManifestResourceStream(resourceName);
if (!string.IsNullOrEmpty(json)) if (stream != null)
{ {
languageResources = JsonSerializer.Deserialize<Dictionary<string, string>>(json) ?? new Dictionary<string, string>(); using StreamReader reader = new(stream);
var json = reader.ReadToEnd();
if (!string.IsNullOrEmpty(json))
{
languageResources = JsonSerializer.Deserialize<Dictionary<string, string>>(json) ?? new Dictionary<string, string>();
}
} }
} }
catch (IOException ex)
{
Console.WriteLine($"Failed to read language resource file: {ex.Message}");
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to parse JSON data: {ex.Message}");
}
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"Failed to load language resources: {ex.Message}"); Console.WriteLine($"Unexpected error occurred: {ex.Message}");
languageResources = []; // 初始化为空字典
} }
} }
/// <summary>
/// 获取系统当前语言的本地化字符串
/// </summary>
/// <param name="key">要翻译的关键字</param>
/// <returns>对应语言的本地化字符串,如果没有找到则返回关键字</returns>
public static string GetLocalizedValue(string key) public static string GetLocalizedValue(string key)
{ {
if (languageResources != null && languageResources.TryGetValue(key, out var translation)) if (languageResources.TryGetValue(key, out var translation))
{ {
return translation; return translation;
} }