这里对Josn解析,用的是Newtonsoft.Json,以下是核心代码
public class JosnConfigHelper
{
private static readonly object fileLock = new object();
private const string DefaultFilePath = "config.json";
/// <summary>
/// 确保文件存在(线程安全)
/// </summary>
private void EnsureFileExists(string filePath = DefaultFilePath)
{
lock (fileLock)
{
if (File.Exists(filePath)) return;
string directory = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
File.WriteAllText(filePath, "{}"); // 创建空JSON对象
}
}
/// <summary>
/// 读取配置值
/// </summary>
public string ReadConfig(string key, string defaultValue = "0", string filePath = DefaultFilePath)
{
EnsureFileExists(filePath);
var configDic = ReadAll(filePath);
string value;
return configDic.TryGetValue(key, out value) ? value : defaultValue;
}
/// <summary>
/// 写入或更新配置
/// </summary>
public void WriteConfig(string key, string value, string filePath = DefaultFilePath)
{
lock (fileLock)
{
EnsureFileExists(filePath);
var configDic = ReadAll(filePath);
configDic[key] = value;
SaveDictionary(configDic, filePath);
}
}
/// <summary>
/// 删除配置项
/// </summary>
public void DeleteConfig(string key, string filePath = DefaultFilePath)
{
lock (fileLock)
{
EnsureFileExists(filePath);
var configDic = ReadAll(filePath);
if (configDic.Remove(key))
{
SaveDictionary(configDic, filePath);
}
}
}
/// <summary>
/// 清空所有配置
/// </summary>
public void ClearConfig(string filePath = DefaultFilePath)
{
lock (fileLock)
{
SaveDictionary(new Dictionary<string, string>(), filePath);
}
}
/// <summary>
/// 读取全部配置
/// </summary>
public Dictionary<string, string> ReadAll(string filePath = DefaultFilePath)
{
EnsureFileExists(filePath);
lock (fileLock)
{
string json = File.ReadAllText(filePath);
try
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json)
?? new Dictionary<string, string>();
}
catch (JsonException)
{
return new Dictionary<string, string>();
}
}
}
/// <summary>
/// 保存字典到文件(私有方法)
/// </summary>
private void SaveDictionary(Dictionary<string, string> dict, string filePath)
{
string json = JsonConvert.SerializeObject(dict, Formatting.Indented);
File.WriteAllText(filePath, json);
}
}本文来自 www.luofenming.com
视频教程,点击进入B站可看高清视频