I would like to store a collection of custom objects in a user.config file and would like to add and remove items from the collection programmatically and then save the modified list back to the configuration file.
My items are of the following simple form:
class UserInfo { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } }
In my app.config I already created a custom section:
<configuration> <configSections> <section name='userInfo' type='UserInfoConfigurationHandler, MyProgram'/> </configSections> <userInfo> <User firstName='John' lastName='Doe' email='john@example.com' /> <User firstName='Jane' lastName='Doe' email='jane@example.com' /> </userInfo> </configuration>
I am also able to read in the settings by implementing IConfigurationSectionHandler:
class UserInfoConfigurationHandler : IConfigurationSectionHandler { public UserInfoConfigurationHandler() { } public object Create(object parent, object configContext, System.Xml.XmlNode section) { List<UserInfo> items = new List<UserInfo>(); System.Xml.XmlNodeList processesNodes = section.SelectNodes('User'); foreach (XmlNode processNode in processesNodes) { UserInfo item = new UserInfo(); item.FirstName = processNode.Attributes['firstName'].InnerText; item.LastName = processNode.Attributes['lastName'].InnerText; item.Email = processNode.Attributes['email'].InnerText; items.Add(item); } return items; } }
I did all this following this article. However, using this approach I’m only able to read the settings from app.config into a List<UserInfo> collection, but I would also need to write a modified list back.
I was searching the documentation without success and now I’m kind of stuck. What am I missing?
I wouldn’t store that kind of data in an app.config, at least not if it’s meant to be updated programatically. Conceptually, it’s for configuration settings, not application data so perhaps you want to store your username and password info in a separate XML file (assuming you can’t or don’t want to use a database)?
Having said that, then I think your best bet is to read in the app.config as a standard XML file, parse it, add the nodes you want and write it back. The built in ConfigurationManager API doesn’t offer a way to write back new settings (which I suppose gives a hint as to Microsoft’s intended use).