Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net web.config appsettings multiple values

Tags:

c#

asp.net

c#-4.0

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.

like image 867
Adam Avatar asked Jun 29 '11 20:06

Adam


3 Answers

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

like image 136
acermate433s Avatar answered Oct 21 '22 09:10

acermate433s


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

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

https://web.archive.org/web/20201202223151/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.

like image 41
TheITGuy Avatar answered Oct 21 '22 10:10

TheITGuy


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);  
}
like image 2
oleksii Avatar answered Oct 21 '22 11:10

oleksii