Skip to content

Commit

Permalink
更新程序内嵌资源文件 (2dust#6101)
Browse files Browse the repository at this point in the history
* fix

* fix

* 移除自述

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

* 小修正

* 修正

* 更正自述

* 应该完成了

* 内嵌资源

* Update LocalizationHelper.cs
  • Loading branch information
Slnanx authored Nov 18, 2024
1 parent 10513e0 commit 1866a59
Showing 1 changed file with 25 additions and 21 deletions.
46 changes: 25 additions & 21 deletions v2rayN/AmazTool/LocalizationHelper.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
using System.Globalization;
using System.Globalization;
using System.Reflection;
using System.Text.Json;

namespace AmazTool
{
public class LocalizationHelper
{
private static Dictionary<string, string> languageResources = new();
private static Dictionary<string, string> languageResources = [];

static LocalizationHelper()
{
// 加载语言资源
LoadLanguageResources();
}

/// <summary>
/// 加载外部 JSON 文件中的语言资源
/// </summary>
private static void LoadLanguageResources()
{
try
Expand All @@ -26,33 +24,39 @@ private static void LoadLanguageResources()
currentLanguage = "en-US";
}

string jsonFilePath = $"{currentLanguage}.json";
if (!File.Exists(jsonFilePath))
{
jsonFilePath = "en-US.json";
}
string resourceName = $"AmazTool.{currentLanguage}.json";
var assembly = Assembly.GetExecutingAssembly();

var json = File.ReadAllText(jsonFilePath);
if (!string.IsNullOrEmpty(json))
using Stream? stream = assembly.GetManifestResourceStream(resourceName);
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)
{
Console.WriteLine($"Failed to load language resources: {ex.Message}");
languageResources = []; // 初始化为空字典
Console.WriteLine($"Unexpected error occurred: {ex.Message}");
}
}

/// <summary>
/// 获取系统当前语言的本地化字符串
/// </summary>
/// <param name="key">要翻译的关键字</param>
/// <returns>对应语言的本地化字符串,如果没有找到则返回关键字</returns>
public static string GetLocalizedValue(string key)
{
if (languageResources != null && languageResources.TryGetValue(key, out var translation))
if (languageResources.TryGetValue(key, out var translation))
{
return translation;
}
Expand Down

0 comments on commit 1866a59

Please sign in to comment.