ShengShengBuXi/ShengShengBuXi.ConsoleApp/Models/AppSettings.cs
2025-03-28 20:03:52 +08:00

72 lines
1.9 KiB
C#

using System.Text.Json;
namespace ShengShengBuXi.ConsoleApp.Models;
/// <summary>
/// 应用程序设置
/// </summary>
public class AppSettings
{
/// <summary>
/// SignalR Hub的URL
/// </summary>
public string SignalRHubUrl { get; set; } = "http://localhost:5000/phonehub";
/// <summary>
/// 配置文件备份路径
/// </summary>
public string ConfigBackupPath { get; set; } = "config.json";
/// <summary>
/// 是否自动连接到服务器
/// </summary>
public bool AutoConnectToServer { get; set; } = true;
/// <summary>
/// 是否允许离线启动
/// </summary>
public bool AllowOfflineStart { get; set; } = false;
/// <summary>
/// 从文件加载设置
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns>应用程序设置</returns>
public static AppSettings LoadFromFile(string filePath)
{
if (!File.Exists(filePath))
{
return new AppSettings();
}
try
{
string json = File.ReadAllText(filePath);
var settings = JsonSerializer.Deserialize<AppSettings>(json);
return settings ?? new AppSettings();
}
catch (Exception ex)
{
Console.WriteLine($"加载应用程序设置失败: {ex.Message}");
return new AppSettings();
}
}
/// <summary>
/// 保存设置到文件
/// </summary>
/// <param name="filePath">文件路径</param>
public void SaveToFile(string filePath)
{
try
{
var options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(this, options);
File.WriteAllText(filePath, json);
}
catch (Exception ex)
{
Console.WriteLine($"保存应用程序设置失败: {ex.Message}");
}
}
}