C#App.Config包含数组或列表之类的数据

Joh*_*ann 18 c# config

如何在app.config中获取数组或列表信息?我希望用户能够尽可能多地放置IP(或根据需要).我的程序只需要在app.config中指定的任何内容.这该怎么做?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ip" value="x" />
    <add key="ip" value="y" />
    <add key="ip" value="z" />
    </appSettings>
</configuration>



public string ip = ConfigurationManager.AppSettings["ip"];
Run Code Online (Sandbox Code Playgroud)

mil*_*uak 29

最简单的方法是在App.config文件中使用逗号分隔列表.当然,您可以编写自己的配置部分,但如果它只是一个字符串数组,请保持简单,这样做的重点是什么.

<configuration>
  <appSettings>
    <add key="ips" value="z,x,d,e" />
  </appSettings>
</configuration>

public string[] ipArray = ConfigurationManager.AppSettings["ips"].Split(',');
Run Code Online (Sandbox Code Playgroud)


Tho*_*mar 15

您可以在设置设计器中设置设置的类型,StringCollection以便创建字符串列表.

截图

您可以稍后访问单个值Properties.Settings.Default.MyCollection[x].

app.config文件中,这看起来如下:

<setting name="MyCollection" serializeAs="Xml">
<value>
    <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <string>Value1</string>
        <string>Value2</string>
    </ArrayOfString>
</value>
</setting>
Run Code Online (Sandbox Code Playgroud)


小智 6

在App.config中,

<add key="YOURKEY" value="a,b,c"/>
Run Code Online (Sandbox Code Playgroud)

在C#中,

STRING阵列:

string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
Run Code Online (Sandbox Code Playgroud)

清单:

 List<string> list = new List<string>(InFormOfStringArray);
Run Code Online (Sandbox Code Playgroud)

  • 为什么不使用`.Split(new char [] {','},StringSplitOptions.RemoveEmptyEntries);`? (4认同)