views:

538

answers:

4

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

To clarify, the collection I am looking for is data like this:

<Illegal Characters>
  <CustomCollection value="?"/>
  <CustomCollection value="#"/>
  <CustomCollection value=","/>
</Illegal Characters>
A: 

I'll describe the way in VB.NET, because I'm sure the C# way is very similar or the same in some cases. Open up the settings.settings file under My Project in the Solution Explorer. Add in the settings that you want, for example "OutputPath". Then, in the code, reference it with

variable = My.Settings.OutputPath

' If a user modifiable setting, you can use:
My.Settings.OutputPath = variable
My.Settings.Save()
HardCode
+1  A: 

If the number of values is small and the names associated with them are fixed, you should be able to store them in the appSettings configuration section and reference them using the ConfigurationManager.AppSettings collection. This will work pretty well for standard key-value pairs. If your data is more complex than that, you might want to define your own configuration section and an associated ConfigurationSectionHandler to parse the data into whatever custom object you want. You'll also probably want to implement a FileSystemWatcher to detect changes to the configuration file and update the configuration of the running application unless it's acceptable to start/stop the service in order to get the new configuration applied.

tvanfosson
+2  A: 

As an alternative, you could store a single string of illgal characters as a regular expression in your config file. That way you don't have to iterate through the characters to check for them being used in a given string - you could do a comparison based on the regex. Might save a bit of cpu and complexity.

Of course, it's easier to use individual XML nodes if the admins are going to edit the file directly. But if they're changing the character list via the application itself, a regex might be good.

ajh1138
+2  A: 

There's a good article on creating a custom configuration section handler that loads the values as a list here.

Basically your IConfigurationSectionHandler's 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;
}
Alconja