Saving a collection of values โ€‹โ€‹in a configuration file

In .Net 3.5 (Windows), I would like to save a small collection of values โ€‹โ€‹in a configuration file. Basically, I need to allow administrators to add and remove values โ€‹โ€‹from this small collection. What do I need to add to the configuration file to store a collection of small values โ€‹โ€‹and how can I read the collection in C #?

To clarify, the collection I'm looking for is this data:

<Illegal Characters> <CustomCollection value="?"/> <CustomCollection value="#"/> <CustomCollection value=","/> </Illegal Characters> 
+4
source share
4 answers

There's a good article on creating a custom configuration section handler that loads values โ€‹โ€‹in a list here .

Basically, your IConfigurationSectionHandler Create method should look something like this:

 public object Create(object parent, object configContext, XmlNode section) { IList<string> illegal = new List<string>(); XmlNodeList processesNodes= section.SelectNodes("CustomCollection"); foreach (XmlNode child in processesNodes) { illegal.Add(child.Attributes["value"].InnerText); } return illegal; } 
+3
source

Alternatively, you can save one line of invalid characters as a regular expression in your configuration file. This way, you do not need to iterate over the characters to verify that they are used in the given string - you can make a comparison based on a regular expression. I can save a little processor and complexity.

Of course, itโ€™s easier to use separate XML nodes if administrators edit the file directly. But if they change the list of characters through the application itself, a regular expression may be good.

+2
source

If the number of values โ€‹โ€‹is small and the names associated with them are fixed, you should be able to store them in the applicationโ€™s configuration section and reference them using the ConfigurationManager .AppSettings. This will work well for standard key-value pairs. If your data is more complex, you can define your own configuration section and its associated ConfigurationSectionHandler to parse the data into all the user object you want. You also probably want to implement FileSystemWatcher to detect changes in the configuration file and update the configuration of the running application if it is not acceptable to start / stop the service in order to apply the new configuration.

+1
source

I will describe the method in VB.NET because I am sure that the C # method is very similar or similar in some cases. Open the settings.settings file in the My Project section of Solution Explorer. Add to the desired settings, for example, "OutputPath". Then in the code, refer to

 variable = My.Settings.OutputPath ' If a user modifiable setting, you can use: My.Settings.OutputPath = variable My.Settings.Save() 
0
source

All Articles