German Latorre
German Latorre

Reputation: 11138

Using appSettings values in other Web.config sections

Is there a way to use appSettings defined properties in any of the other sections in web.config file?

It's quite unpleasant to have to write a value (for instance, an email address) in more than one section, and update it everywhere it occurs whenever a change is done.

Upvotes: 0

Views: 1303

Answers (2)

Dave Anderson
Dave Anderson

Reputation: 12294

If you use $ delimiters in the AppSetting values these can be replaced with the key values they represent from the AppSettings e.g.

<add key="PrivacyPolicyURL" 
  value="$domain$/Default.aspx?siteid=$siteid$&amp;locid=$locid$&amp;tpid=$tpid$"
  />

using the following function to do the substitutions;

public static string GetAppSetting(string key)
{
    string keyValue = ConfigurationManager.AppSettings[key].ToString();

    foreach (System.Text.RegularExpressions.Match match in System.Text.RegularExpressions.Regex.Matches(keyValue, @"\$[\d\D]*?\$"))
    {
        try
        {
            string replaceWith = ConfigurationManager.AppSettings[match.Value.Replace("$", string.Empty)]  ?? string.Empty;
            keyValue = keyValue.Replace(match.Value, replaceWith);
        }
        catch
        {
            keyValue = keyValue.Replace(match.Value, string.Empty);
        }
    }

    return keyValue;
}

So in the example this inserts the AppSettings for domain, siteid, locid and tpid to produce something like; www.mywebsite.com/Default.aspx?siteid=1001&locid=1001&tpid=1001

Upvotes: -1

Kobi
Kobi

Reputation: 138017

You can use String.Format to build your data, and use {0} in the config file, on appropriate places.
Assuming you have basic getters to you're data this should be easy to implement.

For example:

<add key="Mail" value="[email protected]"/>
<add key="LinkFormat" value="[[Mail Us|mailto:{0}]]"/>

And then (stripped down from try/catch, checking data):

public static string GetEmail()
{
    return ConfigurationManager.AppSettings["Mail"];
}

public static string GetEmailLinkformat()
{
    string format = ConfigurationManager.AppSettings["LinkFormat"];
    string mail = GetEmail();
    return String.Format(format, mail);
}

Upvotes: 2

Related Questions