单个配置密钥的多个值

时间:2010-05-12 14:54:01

标签: .net asp.net configuration

我正在尝试使用ConfigurationManager.AppSettings.GetValues()为单个密钥检索多个配置值,但我总是收到一个只包含最后一个值的数组。我的appsettings.config看起来像

<add key="mykey" value="A"/>
<add key="mykey" value="B"/>
<add key="mykey" value="C"/>

我试图用

访问
ConfigurationManager.AppSettings.GetValues("mykey");

但我只是{ "C" }

关于如何解决这个问题的任何想法?

10 个答案:

答案 0 :(得分:41)

尝试

<add key="mykey" value="A,B,C"/>

并且

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

答案 1 :(得分:11)

配置文件将每一行视为一个赋值,这就是为什么你只看到最后一行。当它读取配置时,它会为你的键分配“A”的值,然后是“B”,然后是“C”,并且由于“C”是最后一个值,它就是那个坚持的值。

正如@Kevin建议的那样,最好的方法可能是一个值,其内容是一个可以解析的CSV。

答案 2 :(得分:9)

我知道我迟到但我找到了这个解决方案并且它完美无缺,所以我只想分享。

这就是定义自己的ConfigurationElement

namespace Configuration.Helpers
{
    public class ValueElement : ConfigurationElement
    {
        [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
        public string Name
        {
            get { return (string) this["name"]; }
        }
    }

    public class ValueElementCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ValueElement();
        }


        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ValueElement)element).Name;
        }
    }

    public class MultipleValuesSection : ConfigurationSection
    {
        [ConfigurationProperty("Values")]
        public ValueElementCollection Values
        {
            get { return (ValueElementCollection)this["Values"]; }
        }
    }
}

在app.config中使用您的新部分:

<configSections>
    <section name="PreRequest" type="Configuration.Helpers.MultipleValuesSection,
    Configuration.Helpers" requirePermission="false" />
</configSections>

<PreRequest>
    <Values>
        <add name="C++"/>
        <add name="Some Application"/>
    </Values>
</PreRequest>

并且在检索数据时如下:

var section = (MultipleValuesSection) ConfigurationManager.GetSection("PreRequest");
var applications = (from object value in section.Values
                    select ((ValueElement)value).Name)
                    .ToList();

最后感谢原作post

的作者

答案 3 :(得分:6)

你想做什么是不可能的。您必须以不同方式命名每个键,或者执行value =“A,B,C”之类的操作,并将代码string values = value.split(',')中的不同值分开。

它将始终获取最后定义的键的值(在示例C中)。

答案 4 :(得分:3)

我认为您可以使用自定义配置文件http://www.4guysfromrolla.com/articles/032807-1.aspx

答案 5 :(得分:2)

由于ConfigurationManager.AppSettings.GetValues()方法不起作用,我使用了以下解决方法来获得类似的效果,但需要使用唯一索引对键进行后缀。

var name = "myKey";
var uniqueKeys = ConfigurationManager.AppSettings.Keys.OfType<string>().Where(
    key => key.StartsWith(name + '[', StringComparison.InvariantCultureIgnoreCase)
);
var values = uniqueKeys.Select(key => ConfigurationManager.AppSettings[key]);

这会匹配myKey[0]myKey[1]等键。

答案 6 :(得分:2)

我使用键的命名约定,它就像魅力

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="section1" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>
  <section1>
    <add key="keyname1" value="value1"/>
    <add key="keyname21" value="value21"/>
    <add key="keyname22" value="value22"/>
  </section1>
</configuration>

var section1 = ConfigurationManager.GetSection("section1") as NameValueCollection;
for (int i = 0; i < section1.AllKeys.Length; i++)
{
    //if you define the key is unique then use == operator
    if (section1.AllKeys[i] == "keyName1")
    {
        // process keyName1
    }

    // if you define the key as a list, starting with the same name, then use string StartWith function
    if (section1.AllKeys[i].Startwith("keyName2"))
    {
        // AllKeys start with keyName2 will be processed here
    }
}

答案 7 :(得分:1)

这是完整的解决方案: aspx.cs中的代码

namespace HelloWorld
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UrlRetrieverSection UrlAddresses = (UrlRetrieverSection)ConfigurationManager.GetSection("urlAddresses");
        }
    }

    public class UrlRetrieverSection : ConfigurationSection
    {
        [ConfigurationProperty("", IsDefaultCollection = true,IsRequired =true)]
        public UrlCollection UrlAddresses
        {
            get
            {
                return (UrlCollection)this[""];
            }
            set
            {
                this[""] = value;
            }
        }
    }


    public class UrlCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new UrlElement();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((UrlElement)element).Name;
        }
    }

    public class UrlElement : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
        public string Name
        {
            get
            {
                return (string)this["name"];
            }
            set
            {
                this["name"] = value;
            }
        }

        [ConfigurationProperty("url", IsRequired = true)]
        public string Url
        {
            get
            {
                return (string)this["url"];
            }
            set
            {
                this["url"] = value;
            }
        }

    }
}

并在网络配置

<configSections>
   <section name="urlAddresses" type="HelloWorld.UrlRetrieverSection" />
</configSections>
<urlAddresses>
    <add name="Google" url="http://www.google.com" />
   <add name="Yahoo"  url="http://www.yahoo.com" />
   <add name="Hotmail" url="http://www.hotmail.com/" />
</urlAddresses>

答案 8 :(得分:1)

我对JJS的答复: 配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="List1" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <section name="List2" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  <List1>
    <add key="p-Teapot" />
    <add key="p-drongo" />
    <add key="p-heyho" />
    <add key="p-bob" />
    <add key="p-Black Adder" />
  </List1>
  <List2>
    <add key="s-Teapot" />
    <add key="s-drongo" />
    <add key="s-heyho" />
    <add key="s-bob"/>
    <add key="s-Black Adder" />
  </List2>

</configuration>

检索到字符串[]

的代码
 private void button1_Click(object sender, EventArgs e)
    {

        string[] output = CollectFromConfig("List1");
        foreach (string key in output) label1.Text += key + Environment.NewLine;
        label1.Text += Environment.NewLine;
        output = CollectFromConfig("List2");
        foreach (string key in output) label1.Text += key + Environment.NewLine;
    }
    private string[] CollectFromConfig(string key)
    {
        NameValueCollection keyCollection = (NameValueCollection)ConfigurationManager.GetSection(key);
        return keyCollection.AllKeys;
    }

IMO,这很简单。随意证明我错了:)

答案 9 :(得分:0)

我发现解决方案非常简单。如果所有键都具有相同的值,只需将唯一值用作键并忽略该值即可。

<configSections>
    <section name="appSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false"/>
    <section name="filelist" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false"/>
 </configSections>

<filelist>
    <add key="\\C$\Temp\File01.txt"></add>
    <add key="\\C$\Temp\File02.txt"></add>
    <add key="\\C$\Temp\File03.txt"></add>
    <add key="\\C$\Temp\File04.txt"></add>
    <add key="\\C$\Temp\File05.txt"></add>
    <add key="\\C$\Temp\File06.txt"></add>
    <add key="\\C$\Temp\File07.txt"></add>
    <add key="\\C$\Temp\File08.txt"></add>
</filelist>

然后在代码中只需使用以下内容:

private static List<string> GetSection(string section)
        {
            NameValueCollection sectionValues = ConfigurationManager.GetSection(section) as NameValueCollection;

            return sectionValues.AllKeys.ToList();
        }

结果是:

enter image description here

相关问题