programing

단일 구성 키에 대한 다중 값

javajsp 2023. 8. 7. 22:21

단일 구성 키에 대한 다중 값

사용하려고 합니다.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" }.

이 문제를 해결할 방법이 있습니까?

해라

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

그리고.

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

제가 늦었다는 것은 알지만 이 해결책을 찾았고 완벽하게 작동하기 때문에 공유하고 싶습니다.

당신 자신을 정의하는 것이 중요합니다.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();

마침내 원본 게시물의 작성자 덕분에.

구성 파일은 각 행을 할당처럼 처리하므로 마지막 행만 표시됩니다.구성을 읽을 때 키에 "A", "B", "C"의 값을 할당합니다. "C"가 마지막 값이기 때문에 고정됩니다.

@Kevin이 제안하는 것처럼, 이를 위한 가장 좋은 방법은 CSV 내용을 구문 분석할 수 있는 값일 것입니다.

당신이 원하는 것은 불가능합니다.각 키의 이름을 다르게 지정하거나 value="A,B,C"와 같은 작업을 수행하여 코드에서 서로 다른 값을 구분해야 합니다.string values = value.split(',').

항상 마지막으로 정의된 키 값(예 C)을 선택합니다.

나는 키의 명명 규칙을 사용하고 그것은 매력적으로 작동합니다.

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

사용자 지정 구성 섹션을 사용할 수 있습니다. https://web.archive.org/web/20211020133931/https ://www.4guysfromrolla.com/articles/032807-1.aspx

그 이후로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].

다음은 전체 솔루션: 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>

저는 그 해결책이 매우 간단하다는 것을 알았습니다.모든 키의 값이 동일할 경우 고유한 값을 키로 사용하고 값을 생략합니다.

<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

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, 그것은 매우 간단합니다.제가 틀렸다는 것을 언제든지 증명하세요 :)

언급URL : https://stackoverflow.com/questions/2819964/multiple-values-for-a-single-config-key