📄 config.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace APLib.Common.Configuration
{
public abstract class Config<T> : IConfig where T : ConfigSection, new()
{
/// <summary>
/// 程序文件名
/// </summary>
private string exePath;
/// <summary>
/// 配置段名称
/// </summary>
private string sectionName;
/// <summary>
/// 配置段对象
/// </summary>
protected T section;
/// <summary>
/// 配置文件对象
/// </summary>
protected System.Configuration.Configuration config;
/// <summary>
/// 配置段创建标志
/// </summary>
private bool created;
/// <summary>
/// 获取配置段创建标志
/// true配置段已创建,false配置段未创建
/// </summary>
public bool Created { get { return created; } }
/// <summary>
/// 错误描述
/// </summary>
protected string lastError;
/// <summary>
/// 获取错误描述
/// </summary>
public string LastError { get { return lastError; } }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="sectionName">配置段名称</param>
public Config(string sectionName, string exePath)
{
this.sectionName = sectionName;
this.exePath = exePath;
}
/// <summary>
/// 打开配置文件并创建配置对象
/// </summary>
private void Create()
{
config = ConfigurationManager.OpenExeConfiguration(exePath);
if (config.Sections[sectionName] == null)
{
section = new T();
created = false;
}
else
{
section = config.GetSection(sectionName) as T;
created = true;
}
}
/// <summary>
/// 关闭配置文件
/// </summary>
private void Close()
{
section = null;
config = null;
}
public void Load()
{
try
{
Create();
OnLoad();
lastError = null;
}
catch(Exception e)
{
lastError = e.Message;
}
finally
{
Close();
}
}
public void Save()
{
try
{
Create();
OnSave();
if (!created)
config.Sections.Add(sectionName, section);
config.Save();
lastError = null;
}
catch (Exception e)
{
lastError = e.Message;
}
finally
{
Close();
}
}
/// <summary>
/// 加载自定义配置
/// 用户必须重载此函数以加载自定义配置
/// </summary>
protected abstract void OnLoad();
/// <summary>
/// 保存自定义配置
/// 用户必须重载此函数以保存自定义配置
/// </summary>
protected abstract void OnSave();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -