为什么我动态的在appSettings加入了 key 和value , 第一次调试的时候是没有错的,后来报 app.config 配置系统未能初始化,然后我在bin 文件下面直接运行exe 文件是没有任何问题的,不会报错,就是调试的时候一直会。求帮助~~~
下面是我执行的写操作方法。
/// <summary>
/// 写操作
/// </summary>
/// <param name="AppKey"></param>
/// <param name="AppValue"></param>
public void SetConfigValue(string AppKey, string AppValue)
{
XmlDocument xDoc = new XmlDocument();
//获取可执行文件的路径和名称
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config"); XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings"); xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", AppKey);
xElem2.SetAttribute("value", AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}
下面是我执行的写操作方法。
/// <summary>
/// 写操作
/// </summary>
/// <param name="AppKey"></param>
/// <param name="AppValue"></param>
public void SetConfigValue(string AppKey, string AppValue)
{
XmlDocument xDoc = new XmlDocument();
//获取可执行文件的路径和名称
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config"); XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings"); xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", AppKey);
xElem2.SetAttribute("value", AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}
运行程序时,程序读取的是“程序名.exe.config”。
调试时,程序读取的是“程序名.vshost.exe.config”。
string assemblyConfigFile = Assembly.GetEntryAssembly().Location;
string appDomainConfigFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;你使用这个试试获取配置文件的路径,然后最后使用xml或ConfigurationManager都可以,使用ConfigurationManager的话,记得要RefreshSection,我自己没有亲自验证过,你可以验证下