Storing a String List in App.Config or Web.Config

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();

(The Select and 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[0] = "C:"
drives[1] = "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.)

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Silverlight, Web, Wndows Forms, WPF and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *