programing

app.config config 섹션에서 키 값 쌍을 사전으로 읽는 중

newnotes 2023. 4. 20. 22:41
반응형

app.config config 섹션에서 키 값 쌍을 사전으로 읽는 중

현재 제 어플리케이션에는 다음과 같이 app.config가 설정되어 있습니다.

 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="DeviceSettings">
      <section name="MajorCommands" type="System.Configuration.DictionarySectionHandler"/>
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="ComPort" value="com3"/>
    <add key="Baud" value="9600"/>
    <add key="Parity" value="None"/>
    <add key="DataBits" value="8"/>
    <add key="StopBits" value="1"/>
    <add key="Ping" value="*IDN?"/>
    <add key="FailOut" value="1"/>
  </appSettings>
  <DeviceSettings>
    <MajorCommands>
      <add key="Standby" value="STBY"/>
      <add key="Operate" value="OPER"/>
      <add key="Remote" value="REMOTE"/>
      <add key="Local" value="LOCAL"/>
      <add key="Reset" value="*RST" />
    </MajorCommands>
  </DeviceSettings>
</configuration>

현재 목표는 MajorCommands의 모든 값을 예측하거나 단순히 읽어내는 것입니다.Dictionary<string, string>로 포맷되었다.Dictionary<key, value>. System을 사용하여 여러 가지 접근 방식을 시도했습니다.설정은 되어 있지만, 아무것도 동작하지 않는 것 같습니다.또한 정확한 질문에 대한 자세한 내용은 찾을 수 없었습니다.이 일을 할 수 있는 마땅한 방법이 있을까요?

사용.ConfigurationManager전체 섹션을 얻을 수 있는 클래스app.config로서 제출하다.Hashtable변환할 수 있습니다.Dictionary원하는 경우:

var section = (ConfigurationManager.GetSection("DeviceSettings/MajorCommands") as System.Collections.Hashtable)
                 .Cast<System.Collections.DictionaryEntry>()
                 .ToDictionary(n=>n.Key.ToString(), n=>n.Value.ToString());

에 대한 참조를 추가해야 합니다.System.Configuration조립품

거의 다 왔습니다. MajorCommand를 너무 깊이 중첩했습니다.다음과 같이 변경합니다.

<configuration>
  <configSections>
    <section
      name="MajorCommands"
      type="System.Configuration.DictionarySectionHandler" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <MajorCommands>
    <add key="Standby" value="STBY"/>
    <add key="Operate" value="OPER"/>
    <add key="Remote" value="REMOTE"/>
    <add key="Local" value="LOCAL"/>
    <add key="Reset" value="*RST" />    
  </MajorCommands>
</configuration>

그 후, 다음의 조작이 유효합니다.

var section = (Hashtable)ConfigurationManager.GetSection("MajorCommands");
Console.WriteLine(section["Reset"]);

이것은 사전이 아닌 해시 테이블(타입 세이프가 아님)입니다.네가 원한다면Dictionary<string,string>다음과 같이 변환할 수 있습니다.

Dictionary<string,string> dictionary = section.Cast<DictionaryEntry>().ToDictionary(d => (string)d.Key, d => (string)d.Value);

컨피규레이션파일을 xml 파일로 취급할 수 있습니다.

Dictionary<string, string> myDictionary = new Dictionary<string, string>();
XmlDocument document = new XmlDocument();
document.Load("app.config");
XmlNodeList majorCommands = document.SelectNodes("/configuration/DeviceSettings/MajorCommands/add");

foreach (XmlNode node in majorCommands)
{
    myDictionary.Add(node.Attributes["key"].Value, node.Attributes["value"].Value)
}

문서인 경우.로드하지 마십시오. 구성 파일을 xml 파일로 변환해 보십시오.

언급URL : https://stackoverflow.com/questions/17663305/reading-keyvalue-pairs-into-dictionary-from-app-config-configsection

반응형