简体   繁体   中英

asp.net web.config appsettings multiple values

I have appSetting block that looks like this:

<appSettings>
  <key="site1" value="http://www.thissite.com,site name" />
  <key="site2" value="http://www.thissite.com,site name" />
</appSettings>

I want to populate a dropdown list with the values and text:

value="http://www.thissite.com" text="site name"

I can get them into individual arrays using this:

string[] mykey = ConfigurationManager.AppSettings["site1"].Split(',');
string[] mykey = ConfigurationManager.AppSettings["site2"].Split(',');

however, I want to combine them into one array and then loop through and populate the dropdown in the codebehind. I can populate it this way looping through the individual arrays, but it just seems as if there must be a better way with less code.

Can anyone tell me how?


credit to you all but many thanks to acermate433s' answer below.

NameValueCollection appSettings = ConfigurationManager.AppSettings;
    for (int i = 0; i < appSettings.Count; i++)
    {            
        Response.Write(appSettings.GetKey(i).ToString() + "-" + appSettings[i].ToString());
    }

Obviously, I will do a bit more than just display it.

AppSettings is a NameValueCollection , you could loop through all of its values using for each

Just to give full working sample as this question keeps getting hits

NameValueCollection appSettings = ConfigurationManager.AppSettings;

for (int i = 0; i < appSettings.Count; i++)
{
    string key = appSettings.GetKey(i);
    string value = appSettings.Get(i);  
}

You can extend the config file by creating custom configurations. Essentially you will end up with:

<site name="key1">
   <address value="...1..." />
</site>

http://www.4guysfromrolla.com/articles/020707-1.aspx

Alternatively, you could specify the key as the name of the site and just use http://cephas.net/blog/2003/09/26/extending-webconfig-in-aspnet/ sort of thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM