Winfrom的AppConfig大多数情况下,我们都是用来读取一些简单的配置
偶尔可能会遇到存取一两个变量,这样的情况下,我们不会单独见配置文件,也不会启用ini文件,可能为了方便
顺手用一下appconfig。但是 appconfig读取容易 修改可是很坑的
使用系统只带的方法,可能不会永久保存修改(具体问题请参考C#之app.config、exe.config和vshost.exe.config作用区别)
这种情况下 我们就只能采用xml文件的读写方式去获取和设置值了
方法如下:
public sealed class AppConfigHelper
{
/// <summary>
/// 根据Key取Value值
/// </summary>
/// <param name="key"></param>
public static string GetValue(string key)
{
try
{
//System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
// return config.AppSettings.Settings[key].Value;
return ConfigurationManager.AppSettings[key].ToString().Trim() ?? String.Empty;
}
catch
{
return string.Empty;
}
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
var xNode = xDoc.SelectSingleNode("//appSettings");
var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
if (xElem != null)
{
return xElem.Attributes["value"].Value;
}
return string.Empty;
}
catch (Exception)
{
return string.Empty;
}
}
/// <summary>
/// 根据Key修改Value
/// </summary>
/// <param name="key">要修改的Key</param>
/// <param name="value">要修改为的值</param>
public static void SetValue(string key, string value)
{
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
var xNode = xDoc.SelectSingleNode("//appSettings");
var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
if (xElem != null) xElem.SetAttribute("value", value);
else
{
var xNewElem = xDoc.CreateElement("add");
xNewElem.SetAttribute("key", key);
xNewElem.SetAttribute("value", value);
xNode.AppendChild(xNewElem);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}
catch (Exception)
{
}
try
{
ConfigurationManager.AppSettings.Set(key, value);
//System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
//ConfigurationManager.AppSettings.Set(key, value);
//config.AppSettings.Settings[key].Value = value;
//config.SaveAs("App.config");
}
catch(Exception ex)
{
Log.LogRecorder.AddEventRec(ex.Message);
}
}
}
注释的代码就是系统自带方式读取和写入,这种方式在程序重启后,会丢失掉已经修改后appconfig中的值