读取json文件

This commit is contained in:
Slnanx 2024-11-17 15:06:06 +08:00
parent 7cf9b9f57e
commit 75a4151a5d
6 changed files with 251 additions and 173 deletions

View file

@ -3,10 +3,13 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <PublishSingleFile>true</PublishSingleFile>
<Nullable>enable</Nullable> <SelfContained>true</SelfContained>
<Copyright>Copyright © 2017-2024 (GPLv3)</Copyright> <RuntimeIdentifier>win-x64</RuntimeIdentifier>
<FileVersion>1.3.0</FileVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project> </Project>

View file

@ -1,131 +1,86 @@
using System.Collections.Generic; /**
* 使JSON文件对C#
*
* 使
*
* :
* - System.Collections.Generic
* - System.Globalization
* - System.IO
* - Newtonsoft.Json
*
* :
* - JSON文件en.jsonzh.json
* - JSON文件放置程序同目录中
* -
* - localization.Translate("Try_Terminate_Process") //返回一个 string 字符串
* JSON文件en.json
* {
* "Restart_v2rayN": "Start v2rayN, please wait...",
* "Guidelines": "Please run it from the main application."
* }
*
* JSON文件zh.json
* {
* "Restart_v2rayN": "正在重启,请等待...",
* "Guidelines": "请从主应用运行!"
* }
*
* :
* - NuGet安装了Newtonsoft.Json库
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO;
namespace AmazTool public class Localization
{ {
public class LocalizationHelper private Dictionary<string, string> translations;
public Localization()
{ {
/// <summary> // 获取当前系统的完整文化名称 例zh-CN en-US
/// 获取系统当前语言的本地化字符串 string currentLanguage = CultureInfo.CurrentCulture.Name;
/// </summary>
/// <param name="key">要翻译的关键字</param> // 如果当前语言不是"zh-CN"或"en-US",默认使用英文
/// <returns>对应语言的本地化字符串,如果没有找到则返回关键字</returns> if (currentLanguage != "zh-CN" && currentLanguage != "en-US")
public static string GetLocalizedValue(string key)
{ {
// 定义支持的语言 currentLanguage = "en-US";
HashSet<string> supportedLanguages = ["zh", "en"];
// 获取当前系统语言的 ISO 两字母代码
string currentLanguage = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
// 如果当前语言不在支持的语言列表中,默认使用英文
if (!supportedLanguages.Contains(currentLanguage))
{
currentLanguage = "en";
}
// 尝试获取对应语言的翻译
if (languageResources.TryGetValue(key, out var translations))
{
if (translations.TryGetValue(currentLanguage, out var translation))
{
return translation;
}
}
// 如果未找到翻译,返回关键字本身
return key;
} }
/// <summary> // 加载相应语言的JSON文件
/// 存储不同语言的本地化资源 string jsonFilePath = $"{currentLanguage}.json";
/// </summary> if (!LoadTranslations(jsonFilePath))
public static Dictionary<string, Dictionary<string, string>> languageResources = new()
{ {
{ // 如果加载失败,则使用默认语言
"Guidelines", new Dictionary<string, string> jsonFilePath = "en-US.json";
{ LoadTranslations(jsonFilePath);
{ "en", "Please run it from the main application." }, }
{ "zh", "请从主应用运行!" } }
}
}, private bool LoadTranslations(string jsonFilePath)
{ {
"Upgrade_File_Not_Found", new Dictionary<string, string> try
{ {
{ "en", "Upgrade failed, file not found." }, // 读取JSON文件内容
{ "zh", "升级失败,文件不存在!" } var json = File.ReadAllText(jsonFilePath);
} // 解析JSON内容
}, translations = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
{ return true; // 成功读取和解析JSON文件
"In_Progress", new Dictionary<string, string> }
{ catch (Exception ex)
{ "en", "In progress, please wait..." }, {
{ "zh", "正在进行中,请等待..." } Console.WriteLine($"Failed to load JSON file: {ex.Message}");
} Environment.Exit(1);
}, return false; // 读取或解析JSON文件失败
{ }
"Try_Terminate_Process", new Dictionary<string, string> }
{
{ "en", "Try to terminate the v2rayN process." }, public string Translate(string key)
{ "zh", "尝试结束 v2rayN 进程..." } {
} return translations != null && translations.TryGetValue(key, out string value) ? value : key;
},
{
"Failed_Terminate_Process", new Dictionary<string, string>
{
{ "en", "Failed to terminate the v2rayN.Close it manually,or the upgrade may fail." },
{ "zh", "请手动关闭正在运行的v2rayN否则可能升级失败。" }
}
},
{
"Start_Unzipping", new Dictionary<string, string>
{
{ "en", "Start extracting the update package." },
{ "zh", "开始解压缩更新包..." }
}
},
{
"Success_Unzipping", new Dictionary<string, string>
{
{ "en", "Successfully extracted the update package!" },
{ "zh", "解压缩更新包成功!" }
}
},
{
"Failed_Unzipping", new Dictionary<string, string>
{
{ "en", "Failed to extract the update package!" },
{ "zh", "解压缩更新包失败!" }
}
},
{
"Failed_Upgrade", new Dictionary<string, string>
{
{ "en", "Upgrade failed!" },
{ "zh", "升级失败!" }
}
},
{
"Success_Upgrade", new Dictionary<string, string>
{
{ "en", "Upgrade success!" },
{ "zh", "升级成功!" }
}
},
{
"Information", new Dictionary<string, string>
{
{ "en", "Information" },
{ "zh", "提示" }
}
},
{
"Restart_v2rayN", new Dictionary<string, string>
{
{ "en", "Start v2rayN, please wait..." },
{ "zh", "正在重启,请等待..." }
}
}
};
} }
} }

View file

@ -1,4 +1,34 @@
using System; /**
* 使JSON文件对C#
*
* 使
*
* :
* - System
* - System.Threading
*
* :
* - JSON文件en.jsonzh.json
* - JSON文件放置程序同目录中
* -
* - localization.Translate("Try_Terminate_Process") //返回一个 string 字符串
* JSON文件en.json
* {
* "Restart_v2rayN": "Start v2rayN, please wait...",
* "Guidelines": "Please run it from the main application."
* }
*
* JSON文件zh.json
* {
* "Restart_v2rayN": "正在重启,请等待...",
* "Guidelines": "请从主应用运行!"
* }
*
* :
* - NuGet安装了Newtonsoft.Json库
*/
using System;
using System.Threading; using System.Threading;
namespace AmazTool namespace AmazTool
@ -11,15 +41,20 @@ namespace AmazTool
[STAThread] [STAThread]
private static void Main(string[] args) private static void Main(string[] args)
{ {
var localization = new Localization();
if (args.Length == 0) if (args.Length == 0)
{ {
Console.WriteLine(LocalizationHelper.GetLocalizedValue("Guidelines")); // 不能直接打开更新程序
Console.WriteLine(localization.Translate("Guidelines"));
Thread.Sleep(5000); Thread.Sleep(5000);
return; return;
} }
// 解析并拼接命令行参数以获取文件名
var fileName = Uri.UnescapeDataString(string.Join(" ", args)); var fileName = Uri.UnescapeDataString(string.Join(" ", args));
// 调用升级方法进行文件处理
UpgradeApp.Upgrade(fileName); UpgradeApp.Upgrade(fileName);
} }
} }
} }

View file

@ -1,4 +1,37 @@
using System; /**
* 使JSON文件对C#
*
* 使
*
* :
* - System
* - System.Collections.Generic
* - System.Globalization
* - System.IO
* - Newtonsoft.Json
*
* :
* - JSON文件en.jsonzh.json
* - JSON文件放置程序同目录中
* -
* - localization.Translate("Try_Terminate_Process") //返回一个 string 字符串
* JSON文件en.json
* {
* "Restart_v2rayN": "Start v2rayN, please wait...",
* "Guidelines": "Please run it from the main application."
* }
*
* JSON文件zh.json
* {
* "Restart_v2rayN": "正在重启,请等待...",
* "Guidelines": "请从主应用运行!"
* }
*
* :
* - NuGet安装了Newtonsoft.Json库
*/
using System;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
@ -9,41 +42,64 @@ namespace AmazTool
{ {
internal class UpgradeApp internal class UpgradeApp
{ {
// 定义常量
private static readonly string V2rayN = "v2rayN";
private static readonly string SplitKey = "/";
public static void Upgrade(string fileName) public static void Upgrade(string fileName)
{ {
Console.WriteLine(fileName); var localization = new Localization();
Console.WriteLine(fileName);
Thread.Sleep(9000); Thread.Sleep(9000);
if (!File.Exists(fileName)) if (!File.Exists(fileName))
{ {
Console.WriteLine(LocalizationHelper.GetLocalizedValue("Upgrade_File_Not_Found")); // 如果文件不存在,输出相应的本地化信息
Console.WriteLine(localization.Translate("Upgrade_File_Not_Found"));
return; return;
} }
Console.WriteLine(LocalizationHelper.GetLocalizedValue("Try_Terminate_Process")); // 尝试终止进程
TerminateProcess(localization);
// 解压缩更新包
ExtractUpdatePackage(fileName, localization);
// 重启进程
Console.WriteLine(localization.Translate("Restart_v2rayN"));
Thread.Sleep(9000);
RestartProcess();
}
private static void TerminateProcess(Localization localization)
{
Console.WriteLine(localization.Translate("Try_Terminate_Process"));
try try
{ {
var existing = Process.GetProcessesByName(V2rayN); var processes = Process.GetProcessesByName(V2rayN);
foreach (var pp in existing) foreach (var process in processes)
{ {
pp?.Kill(); process?.Kill();
pp?.WaitForExit(1000); process?.WaitForExit(1000);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
// Access may be denied without admin right. The user may not be an administrator. // 如果无法终止进程,输出相应的本地化信息和错误堆栈
Console.WriteLine(LocalizationHelper.GetLocalizedValue("Failed_Terminate_Process") + ex.StackTrace); Console.WriteLine(localization.Translate("Failed_Terminate_Process") + ex.StackTrace);
} }
}
private static void ExtractUpdatePackage(string fileName, Localization localization)
{
Console.WriteLine(localization.Translate("Start_Unzipping"));
StringBuilder errorLog = new();
Console.WriteLine(LocalizationHelper.GetLocalizedValue("Start_Unzipping"));
StringBuilder sb = new();
try try
{ {
string thisAppOldFile = $"{GetExePath()}.tmp"; string backupFilePath = $"{GetExePath()}.tmp";
File.Delete(thisAppOldFile); File.Delete(backupFilePath);
string splitKey = "/";
using ZipArchive archive = ZipFile.OpenRead(fileName); using ZipArchive archive = ZipFile.OpenRead(fileName);
foreach (ZipArchiveEntry entry in archive.Entries) foreach (ZipArchiveEntry entry in archive.Entries)
@ -51,22 +107,14 @@ namespace AmazTool
try try
{ {
if (entry.Length == 0) if (entry.Length == 0)
{
continue; continue;
}
Console.WriteLine(entry.FullName); Console.WriteLine(entry.FullName);
var lst = entry.FullName.Split(splitKey); string fullPath = GetEntryFullPath(entry.FullName);
if (lst.Length == 1) continue; BackupExistingFile(fullPath, backupFilePath);
string fullName = string.Join(splitKey, lst[1..lst.Length]);
if (string.Equals(GetExePath(), GetPath(fullName), StringComparison.OrdinalIgnoreCase)) string entryOutputPath = GetPath(fullPath);
{
File.Move(GetExePath(), thisAppOldFile);
}
string entryOutputPath = GetPath(fullName);
Directory.CreateDirectory(Path.GetDirectoryName(entryOutputPath)!); Directory.CreateDirectory(Path.GetDirectoryName(entryOutputPath)!);
entry.ExtractToFile(entryOutputPath, true); entry.ExtractToFile(entryOutputPath, true);
@ -74,23 +122,39 @@ namespace AmazTool
} }
catch (Exception ex) catch (Exception ex)
{ {
sb.Append(ex.StackTrace); errorLog.Append(ex.StackTrace);
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(LocalizationHelper.GetLocalizedValue("Failed_Upgrade") + ex.StackTrace); // 如果解压失败,输出相应的本地化信息和错误堆栈
//return; Console.WriteLine(localization.Translate("Failed_Upgrade") + ex.StackTrace);
}
if (sb.Length > 0)
{
Console.WriteLine(LocalizationHelper.GetLocalizedValue("Failed_Upgrade") + sb.ToString());
//return;
} }
Console.WriteLine(LocalizationHelper.GetLocalizedValue("Restart_v2rayN")); if (errorLog.Length > 0)
Thread.Sleep(9000); {
// 如果有任何错误记录,输出相应的本地化信息和错误日志
Console.WriteLine(localization.Translate("Failed_Upgrade") + errorLog.ToString());
}
}
private static void BackupExistingFile(string fullPath, string backupFilePath)
{
if (string.Equals(GetExePath(), fullPath, StringComparison.OrdinalIgnoreCase))
{
File.Move(GetExePath(), backupFilePath);
}
}
private static string GetEntryFullPath(string entryName)
{
var parts = entryName.Split(SplitKey);
return parts.Length > 1 ? string.Join(SplitKey, parts[1..]) : entryName;
}
private static void RestartProcess()
{
Process process = new() Process process = new()
{ {
StartInfo = new() StartInfo = new()
@ -115,14 +179,7 @@ namespace AmazTool
private static string GetPath(string fileName) private static string GetPath(string fileName)
{ {
string startupPath = StartupPath(); return string.IsNullOrEmpty(fileName) ? StartupPath() : Path.Combine(StartupPath(), fileName);
if (string.IsNullOrEmpty(fileName))
{
return startupPath;
}
return Path.Combine(startupPath, fileName);
} }
private static string V2rayN => "v2rayN";
} }
} }

View file

@ -0,0 +1,14 @@
{
"Restart_v2rayN": "Start v2rayN, please wait...",
"Guidelines": "Please run it from the main application.",
"Upgrade_File_Not_Found": "Upgrade failed, file not found.",
"In_Progress": "In progress, please wait...",
"Try_Terminate_Process": "Try to terminate the v2rayN process.",
"Failed_Terminate_Process": "Failed to terminate the v2rayN.Close it manually,or the upgrade may fail.",
"Start_Unzipping": "Start extracting the update package.",
"Success_Unzipping": "Successfully extracted the update package!",
"Failed_Unzipping": "Failed to extract the update package!",
"Failed_Upgrade": "Upgrade failed!",
"Success_Upgrade": "Upgrade success!",
"Information": "Information"
}

View file

@ -0,0 +1,14 @@
{
"Restart_v2rayN": "正在重启,请等待...",
"Guidelines": "请从主应用运行!",
"Upgrade_File_Not_Found": "升级失败,文件不存在!",
"In_Progress": "正在进行中,请等待...",
"Try_Terminate_Process": "尝试结束 v2rayN 进程...",
"Failed_Terminate_Process": "请手动关闭正在运行的v2rayN否则可能升级失败。",
"Start_Unzipping": "开始解压缩更新包...",
"Success_Unzipping": "解压缩更新包成功!",
"Failed_Unzipping": "解压缩更新包失败!",
"Failed_Upgrade": "升级失败!",
"Success_Upgrade": "升级成功!",
"Information": "提示"
}