Files
FATrace/FATrace.Com/ConfigHelper.cs
2025-10-10 17:54:53 +08:00

224 lines
7.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FATrace.Com
{
public class ConfigHelper
{
private static readonly Configuration AppConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
/// <summary>
/// 根据 key 读取字符串配置。若不存在或为空,抛出带有明确提示的信息。
/// </summary>
public static string GetRequiredString(string configKey)
{
if (string.IsNullOrWhiteSpace(configKey))
{
throw new ArgumentException("配置键不能为空", nameof(configKey));
}
try
{
var raw = ConfigurationManager.AppSettings[configKey];
if (raw == null)
{
throw new ConfigurationErrorsException($"未找到配置项: {configKey}");
}
var value = raw.Trim();
if (value.Length == 0)
{
throw new ConfigurationErrorsException($"配置项为空: {configKey}");
}
return value;
}
catch (ConfigurationErrorsException)
{
throw;
}
catch (Exception ex)
{
throw new ConfigurationErrorsException($"读取配置项失败: {configKey}", ex);
}
}
/// <summary>
/// 根据Key取Value值
/// </summary>
/// <param name="key"></param>
public static string GetValue(string key)
{
return ConfigurationManager.AppSettings[key].ToString().Trim();
}
/// <summary>
/// 根据 key 读取字符串配置,不存在时返回默认值。
/// </summary>
public static string GetStringOrDefault(string configKey, string defaultValue)
{
if (string.IsNullOrWhiteSpace(configKey)) return defaultValue;
try
{
var raw = ConfigurationManager.AppSettings[configKey];
return string.IsNullOrWhiteSpace(raw) ? defaultValue : raw.Trim();
}
catch
{
return defaultValue;
}
}
/// <summary>
/// 尝试读取字符串配置。
/// </summary>
public static bool TryGetString(string configKey, out string value)
{
value = string.Empty;
if (string.IsNullOrWhiteSpace(configKey)) return false;
try
{
var raw = ConfigurationManager.AppSettings[configKey];
if (raw == null) return false;
value = raw.Trim();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 读取 int 配置,支持默认值。
/// </summary>
public static int GetIntOrDefault(string configKey, int defaultValue)
{
var raw = GetStringOrDefault(configKey, string.Empty);
if (string.IsNullOrWhiteSpace(raw)) return defaultValue;
return int.TryParse(raw, out var result) ? result : defaultValue;
}
/// <summary>
/// 读取 bool 配置,支持默认值。
/// </summary>
public static bool GetBoolOrDefault(string configKey, bool defaultValue)
{
var raw = GetStringOrDefault(configKey, string.Empty);
if (string.IsNullOrWhiteSpace(raw)) return defaultValue;
return bool.TryParse(raw, out var result) ? result : defaultValue;
}
/// <summary>
/// 读取 TimeSpan 配置(毫秒或标准格式),支持默认值。
/// </summary>
public static TimeSpan GetTimeSpanOrDefault(string configKey, TimeSpan defaultValue)
{
var raw = GetStringOrDefault(configKey, string.Empty);
if (string.IsNullOrWhiteSpace(raw)) return defaultValue;
// 优先解析为毫秒整数
if (int.TryParse(raw, out var milliseconds))
{
return TimeSpan.FromMilliseconds(milliseconds);
}
return TimeSpan.TryParse(raw, out var ts) ? ts : defaultValue;
}
/// <summary>
/// 根据Key修改Value保存到 App.config
/// </summary>
public static void SetValue(string configKey, string newValue)
{
if (string.IsNullOrWhiteSpace(configKey))
{
throw new ArgumentException("配置键不能为空", nameof(configKey));
}
try
{
if (AppConfiguration.AppSettings.Settings[configKey] == null)
{
AppConfiguration.AppSettings.Settings.Add(configKey, newValue ?? string.Empty);
}
else
{
AppConfiguration.AppSettings.Settings[configKey].Value = newValue ?? string.Empty;
}
AppConfiguration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
catch (ConfigurationErrorsException)
{
throw;
}
catch (Exception ex)
{
throw new ConfigurationErrorsException($"写入配置项失败: {configKey}", ex);
}
}
/// <summary>
/// 添加新的 Key/Value。
/// </summary>
public static void Add(string configKey, string value)
{
if (string.IsNullOrWhiteSpace(configKey))
{
throw new ArgumentException("配置键不能为空", nameof(configKey));
}
try
{
AppConfiguration.AppSettings.Settings.Add(configKey, value ?? string.Empty);
AppConfiguration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
catch (ConfigurationErrorsException)
{
throw;
}
catch (Exception ex)
{
throw new ConfigurationErrorsException($"添加配置项失败: {configKey}", ex);
}
}
/// <summary>
/// 根据 Key 删除项。
/// </summary>
public static void Remove(string configKey)
{
if (string.IsNullOrWhiteSpace(configKey)) return;
try
{
AppConfiguration.AppSettings.Settings.Remove(configKey);
AppConfiguration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
catch (Exception ex)
{
throw new ConfigurationErrorsException($"删除配置项失败: {configKey}", ex);
}
}
/// <summary>
/// 读取必需的连接字符串配置。
/// </summary>
public static string GetRequiredConnectionString(string configKey)
{
var cs = GetRequiredString(configKey);
if (cs.IndexOf("Initial Catalog", StringComparison.OrdinalIgnoreCase) < 0 &&
cs.IndexOf("Database", StringComparison.OrdinalIgnoreCase) < 0)
{
throw new ConfigurationErrorsException($"连接字符串看起来不完整: {configKey}");
}
return cs;
}
}
}