/// <summary>
/// XML配置文件读取键值对,实际上可以使用系统的方法:
/// System.Configuration.ConfigurationManager.AppSettings[key]
/// 但是,如果更新后,没使用 System.Configuration.ConfigurationManager.RefreshSection("appSettings");
/// 会造成文件更新了,但配置读取还是之前内存数据。
/// </summary>
/// <param name="xmlfile"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string OP_XML_ReadKeyValue(string xmlfile, string key)
{
string result = "";
try
{
XmlDocument doc01 = new XmlDocument();
doc01.Load(xmlfile);
//找出名称为“add”的所有元素
XmlNodeList nodes01 = doc01.GetElementsByTagName("add");
for (int i = 0; i < nodes01.Count; i++)
{
//获得将当前元素的key属性
XmlAttribute att = nodes01[i].Attributes["key"];
//根据元素的第一个属性来判断当前的元素是不是目标元素
if (att == null)
{
continue;
}
if (att.Value == key)
{
//对目标元素中的第二个属性赋值
att = nodes01[i].Attributes["value"];
result = att.Value;
break;
}
}
//保存上面的修改
doc01.Save(xmlfile);
return result;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// XML配置文件写入键值对操作
/// </summary>
/// <param name="xmlfile">文件路径全称</param>
/// <param name="key"></param>
/// <param name="newValue"></param>
/// <returns></returns>
public static bool OP_XML_WriteKeyValue(string xmlfile,string key,string newValue)
{
try
{
XmlDocument doc01 = new XmlDocument();
doc01.Load(xmlfile);
//找出名称为“add”的所有元素
XmlNodeList nodes01 = doc01.GetElementsByTagName("add");
for (int i = 0; i < nodes01.Count; i++)
{
//获得将当前元素的key属性
XmlAttribute att = nodes01[i].Attributes["key"];
//根据元素的第一个属性来判断当前的元素是不是目标元素
if (att == null)
{
continue;
}
if (att.Value == key)
{
//对目标元素中的第二个属性赋值
att = nodes01[i].Attributes["value"];
att.Value = newValue;
break;
}
}
//保存上面的修改
doc01.Save(xmlfile);
return true;
}
catch (Exception ex)
{
return false;
}
}
参考了:C# winform把新值写入app.config文件_nudt_qxx的博客-CSDN博客
wo做了整合。