【C#】配置文件类模板

本文介绍了一个用于应用程序配置管理的AppConfig类。该类通过单例模式实现,使用XML文件存储配置信息,包括关键的更新时间间隔参数。文章深入探讨了类的属性、方法和异常处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class AppConfig
{
    private static Lazy<AppConfig> _config = new Lazy<AppConfig>(() => new AppConfig());

    public static AppConfig GetInstance() => _config.Value;
    
    private string _configFilePath = AppDomain.CurrentDomain.BaseDirectory + "AppConfig.xml";

    private XDocument _xml;

    private AppConfig()
    {
        CheckConfig(_configFilePath);
        OnloadConfig(ref _xml, _configFilePath);
    }

    private string _interval;
    public string Interval
    {
        get
        {
            try
            {
                _interval = _xml.Root.Element("Interval").Value;
            }
            catch (Exception e)
            {
                throw new Exception($"[读取Interval参数失败][{e.Message}]");
            }
            return _interval;
        }
    }

    private void OnloadConfig(ref XDocument xd, string path)
    {
        if (File.Exists(path))
        {
            xd = XDocument.Load(path);
        }
    }

    private void CheckConfig(string filePath)
    {
        if (File.Exists(filePath))
            return;
        XDocument xml = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
        XElement root = new XElement("RptMatConfig");
        root.Add(new XComment("更新时间(秒)"));
        root.Add(new XElement("Interval", "10"));
        xml.Add(root);
        //保存文档
        xml.Save(filePath);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值