代码实现:
public class ConfigFile
{
struct waitSavaConfigObject
{
public string ConfigContent;
public bool isBuilt; //指示该配置是否已经构建
public waitSavaConfigObject()
{
ConfigContent = "";
isBuilt = false;
}
}
//初始化日志输出工具
Log logger = new Log();
Hashtable configTable = new Hashtable();
string configFile = "";
public static string CRLF = "\r\n";
waitSavaConfigObject wsco = new waitSavaConfigObject();
public ConfigFile(string configFilePath) {
configFile = configFilePath;
if (!File.Exists(configFile))
{
//若文件不存在则创建一个文件,close方法用于关闭流,防止后续占用抛异常
File.Create(configFile).Close();
}
else
{
//加载配置文件到HashTable
LoadConfig();
}
}
private void LoadConfig()
{
string config = File.ReadAllText(configFile);
//使用\r\r作为分割行的符号
string[] ConfigList = config.Split("\r\n");
foreach (string ConfigItem in ConfigList)
{
if (ConfigItem.Trim() != "" )
{
try
{
configTable.Add(ConfigItem.Split("=")[0], ConfigItem.Split("=")[1]);
}
catch (IndexOutOfRangeException e)
{
logger.Error("读取配置文件时出现错误:" + ConfigItem + "\r\n" + e.Message);
}
catch (Exception e)
{
logger.Error("未处理的异常:" + e.Message);
}
}
}
}
public void SetConfig(string key,string value)
{
configTable[key] = value;
wsco.isBuilt = false;
}
public string GetConfig(string key)
{
if (configTable.ContainsKey(key))
{
return configTable[key].ToString();
}
else
{
logger.Warning($"尝试访问一个不存在的键:{key}");
return null;
}
}
public bool WriteConfig()
{
BuildConfigContent();
if (wsco.isBuilt)
{
try
{
File.WriteAllText(configFile, wsco.ConfigContent);
}
catch (Exception e)
{
logger.Error(e.Message + CRLF + "Type:" + e.GetType() + CRLF + e.StackTrace);
return false;
}
logger.Success("配置文件保存成功.");
return true;
}
else
{
logger.Warning("尝试保存一个未构建的配置文件对象.");
return false;
}
}
private void BuildConfigContent() //把HashTable转换为键值对格式
{
string configContent = "";
try
{
foreach (DictionaryEntry de in configTable)
{
configContent += de.Key + "=" + de.Value + "\r\n";
}
}
catch (Exception e)
{
logger.Error(e.Message);
return;
}
wsco.ConfigContent = configContent;
wsco.isBuilt = true;
}
}