67 lines
2.0 KiB
C#
67 lines
2.0 KiB
C#
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace videoGather
|
|
{
|
|
public static class ConfigHelper
|
|
{
|
|
|
|
private static readonly string ConfigFolder =
|
|
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");
|
|
|
|
/// <summary>
|
|
/// 保存配置到指定名称的配置文件
|
|
/// </summary>
|
|
/// <typeparam name="T">配置数据类型</typeparam>
|
|
/// <param name="configName">配置文件名(无需扩展名)</param>
|
|
/// <param name="data">配置数据</param>
|
|
public static void Save<T>(string configName, T data)
|
|
{
|
|
if (!Directory.Exists(ConfigFolder))
|
|
{
|
|
Directory.CreateDirectory(ConfigFolder);
|
|
}
|
|
|
|
var filePath = GetConfigPath(configName);
|
|
var json = JsonConvert.SerializeObject(data, Formatting.Indented);
|
|
File.WriteAllText(filePath, json);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取指定配置文件的配置数据
|
|
/// </summary>
|
|
/// <typeparam name="T">配置数据类型</typeparam>
|
|
/// <param name="configName">配置文件名(无需扩展名)</param>
|
|
/// <param name="defaultValue">当配置不存在时的默认值</param>
|
|
public static T Load<T>(string configName, T defaultValue = default)
|
|
{
|
|
var filePath = GetConfigPath(configName);
|
|
|
|
if (!File.Exists(filePath))
|
|
{
|
|
return defaultValue;
|
|
}
|
|
|
|
try
|
|
{
|
|
var json = File.ReadAllText(filePath);
|
|
return JsonConvert.DeserializeObject<T>(json);
|
|
}
|
|
catch
|
|
{
|
|
return defaultValue;
|
|
}
|
|
}
|
|
|
|
private static string GetConfigPath(string configName)
|
|
{
|
|
return Path.Combine(ConfigFolder, $"{configName}.config.json");
|
|
}
|
|
}
|
|
}
|