app.config只是一个XML文件...因此,对于简单配置文件的快速简便解决方案,只需将其视为:
using System.Xml.Linq; // Create a list just in case you want to remove specific elements later List<XElement> toRemove = new List<XElement>(); // Load the config file XDocument doc = XDocument.Load("app.config"); // Get the appSettings element as a parent XContainer appSettings = doc.Element("configuration").Element("appSettings"); // step through the "add" elements foreach (XElement xe in appSettings.Elements("add")) { // Get the values string addKey = xe.Attribute("key").Value; string addValue = xe.Attribute("value").Value; // if you want to remove it... if (addValue == "something") { // you can't remove it directly in the foreach loop since it breaks the enumerable // add it to a list and do it later toRemove.Add(xe); } } // Remove the elements you've selected foreach (XElement xe in toRemove) { xe.Remove(); } // Add any new Elements that you want appSettings.Add(new XElement("add", new XAttribute("key", "\\inculde"), new XAttribute("value", "chapX")));
如果您确切地知道自己想要做什么,那么您可以使用更具针对性的解决方案。
但是,对于您的场景,您可能希望将此添加元素加载到集合中,根据需要处理它们(添加/删除/更新等...),然后将它们再次作为“添加”元素重新写回.config文件中。