Wednesday, October 26, 2016

How to create a dictionary like mapping in web.config file in .Net Development

it is quite convenience to setup a dictoniary mapping in the configuration file. so we did not have to make any code change if we have to add more mapping in the future.


it is okay to use the appSettings to performance this task. However it is better to create a new section and store those mapping. it is quute easy to complete this approach.

step one. create a new section name under the configSections tag


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

step two. set up the new sections in the web.config file

<PdfPrintMap>
    <add key="Doc1" value="Doc1.pdf" />
    <add key="Doc2" value="Doc2.pdf" />
    <add key="Doc3 value="Doc3.pdf" />
    <add key="Doc4" value="Doc4.pdf" />
  </PdfPrintMap>

setp three implement a method to access the section and retrieve the values by providing the section name, and the key. as a result, when we have the key, we can directly load the value.

   public static string GetCustomSectionValue(string sectionName,string key)
        {
            NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection(sectionName);
            if (section != null)
            {
                return section[key];
            }
            return string.Empty;
        }

No comments:

Post a Comment