How do I store a dictionary object in my web.config file?

Why reinvent the wheel? The AppSettings section is designed for exactly the purpose of storing dictionary-like data in your config file.

If you don’t want to put too much data in your AppSettings section, you can group your related values into their own section as follows:

<configuration>
  <configSections>
    <section 
      name="MyDictionary" 
      type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <MyDictionary>
     <add key="name1" value="value1" />
     <add key="name2" value="value2" />
     <add key="name3" value="value3" />
     <add key="name4" value="value4" />
  </MyDictionary>
</configuration>

You can access elements in this collection using

using System.Collections.Specialized;
using System.Configuration;

public string GetName1()
{
    NameValueCollection section =
        (NameValueCollection)ConfigurationManager.GetSection("MyDictionary");
    return section["name1"];
}

Leave a Comment