private const string config="configuration", settings="appSettings";
private const string nodeName="add", keyAttr="key", valAttr="value";
public bool SetConfigValue(string key, string val)
{
return(SetConfigValue(Assembly.GetExecutingAssembly().Location+".config", key, val));
}
public bool SetConfigValue(string path, string key, string val)
{ XmlDocument doc=new XmlDocument();
try
{ doc.Load(path); // загрузить документ из файла конфигурации
foreach(XmlElement nd in doc[config][settings])
{ if(nd.Name!=nodeName || nd.GetAttribute(keyAttr)!=key) continue;
// установить новое значение атрибута
nd.SetAttribute(valAttr, val);
doc.Save(path); // сохранить документ в файл конфигурации
return(true);
}
// элемент не нашли - добавить новый
XmlElement nn=doc.CreateElement(nodeName);
nn.SetAttribute(keyAttr, key); // ключ
nn.SetAttribute(valAttr, val); // значение
doc[config][settings].AppendChild(nn);
doc.Save(path); // сохранить документ в файл конфигурации
return(true);
}
catch(Exception ex)
{ /* обработка ошибок */
return(false);
}
} |