App.Config and Web.Config allow you to easily store configuration for use at runtime. The facility they expose is key/value pairs, like so:
<appSettings> <add key="drive" value="C:\" /> </appsettings>
At runtime, you can access these values like so:
System.Configuration.ConfigurationManager.AppSettings["drive"]; // returns "C:\"
This is great for storing a few key/value pairs for different uses. But what if you wanted to store a list of strings? In our example, what if you wanted to store multiple drives? How can you do this?
One solution is to use multiple key/value pairs, like so:
<appSettings> <add key="drive1" value="C:\" /> <add key="drive2" value="D:\" /> </appsettings>
Of course, this means you have to individually access the values at runtime; you can’t just grab them all into a single array or string.
The answer is surprisingly easy: just store the value as a delimited list and split it at runtime, like so:
<appSettings> <add key="drives" value="C:, D:" /> </appsettings>
And at runtime:
string drives = ConfigurationManager.AppSettings["drives"].Split(',').Select(s => s.Trim()).ToArray();
Trim calls allow us to use white-spaces in the config file, and get a trimmed, whitespace-free list of drives.) This code would return, as expected, a string array:
drives = "C:" drives = "D:"
Easy, right? But not so obvious. In fact, the obvious answer to this is to use a custom section. Personally, I feel that this is overkill for asimple list of strings, ints, or other basic types. (Technically, you can shove any serializable class in here; as long as you have a non-ambiguous delimiter, you’re good.)