Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 单个配置键的多个值_.net_Asp.net_Configuration - Fatal编程技术网

.net 单个配置键的多个值

.net 单个配置键的多个值,.net,asp.net,configuration,.net,Asp.net,Configuration,我试图使用ConfigurationManager.AppSettings.GetValues()检索单个键的多个配置值,但我总是只接收最后一个值的数组。我的appsettings.config看起来像 <add key="mykey" value="A"/> <add key="mykey" value="B"/> <add key="mykey" value="C"/> 但是我只得到了{“C”} 关于如何解决这个问题有什么想法吗?你想做什么是不可能的。您

我试图使用
ConfigurationManager.AppSettings.GetValues()
检索单个键的多个配置值,但我总是只接收最后一个值的数组。我的
appsettings.config
看起来像

<add key="mykey" value="A"/>
<add key="mykey" value="B"/>
<add key="mykey" value="C"/>
但是我只得到了
{“C”}


关于如何解决这个问题有什么想法吗?

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

它将始终拾取上次定义的键的值(在您的示例C中)。

试试看

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

配置文件将每一行视为一个赋值,这就是为什么您只看到最后一行。当它读取配置时,它会给你的键分配一个值“A”,然后是“B”,然后是“C”,因为“C”是最后一个值,所以它会粘住


正如@Kevin所建议的,最好的方法可能是一个内容为CSV的值,您可以对其进行解析。

我认为,您可以使用自定义配置节

因为
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]);
var name=“myKey”;
var uniqueKeys=ConfigurationManager.AppSettings.Keys.OfType()。其中(
key=>key.StartsWith(name+'[',StringComparison.InvariantCultureIgnoreCase)
);
var values=uniqueKeys.Select(key=>ConfigurationManager.AppSettings[key]);

这将匹配像
myKey[0]
myKey[1]

这样的键。我知道我迟到了,但我找到了这个解决方案,它非常有效,所以我只想与大家分享

这都是关于定义自己的
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>
最后,感谢原

的作者,以下是完整的解决方案: 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;
            }
        }

    }
}
和在web配置中

<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>

我对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>

在我看来,这是很简单的。请随意证明我错了:)

我使用钥匙的命名约定,它就像一个符咒

<?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”)作为NameValueCollection;
对于(int i=0;i
我发现解决方案非常简单。如果所有键都具有相同的值,只需使用唯一的值作为键,并忽略该值

<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>


那么,
ConfigurationManager.AppSettings.GetValues()
有什么意义呢?@Yuck one质疑底层NameValueCollection类的意义——它支持每个键多个值,但实际上不允许每个键设置多个值(AppSettings必须在内部使用set indexer)-这是问题的真正原因,而不是GetValues()只返回一个值。如果只有一个值,则会出现任何未找到的字符错误?ConfigurationManager.ConnectionString使您能够在否定此问题的所有答案的列表中循环(我知道它不是连接字符串,但您可以这样使用它)感谢CubeJockey进行重新对齐。这是一个很好的标准检索,通过指定键和值,我认为这是最干净的解决方案。它还允许可能已经包含许多常用分隔符的值。我实现了它并解决了我的问题,我不必担心有一天可能需要一个值使用一个特定的分隔符。
<?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;
    }
<?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
    }
}
<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();
        }