简体   繁体   English

asp.net web.config appsettings 多个值

[英]asp.net web.config appsettings multiple values

I have appSetting block that looks like this:我有如下所示的appSetting块:

<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" value="http://www.thissite.com" text="站点名称"

I can get them into individual arrays using this:我可以使用以下方法将它们放入单独的 arrays 中:

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.我可以通过单个 arrays 循环填充它,但似乎必须有更好的方法和更少的代码。

Can anyone tell me how?谁能告诉我怎么做?


credit to you all but many thanks to acermate433s' answer below.感谢acermate433s 在下面的回答

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 AppSettings 是一个NameValueCollection ,您可以使用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 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.或者,您可以将密钥指定为站点的名称,然后使用http://cephas.net/blog/2003/09/26/extending-webconfig-in-aspnet/ 之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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