【问题标题】:C# App.Config with array or list like dataC# App.Config 与数组或类似数据的列表
【发布时间】:2014-06-23 07:50:43
【问题描述】:

如何在 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"];

【问题讨论】:

标签: c# config


【解决方案1】:

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

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

public string[] ipArray = ConfigurationManager.AppSettings["ips"].Split(',');

【讨论】:

    【解决方案2】:

    您可以在设置设计器中将设置的类型设置为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>
    

    【讨论】:

    • 当我尝试使用 Properties.Settings.MyCollection[x] 调用设置时,它显示非静态字段、方法或属性需要对象引用?有什么想法吗?
    • 啊,明白了,类似于“StringCollection someRegKeys = new Properties.Settings().RegKeys;”
    • 我的回答有误。必须是Properties.Settings.Default.xyz
    • 这比使用字符串解析更好。在设置设计器中,使用“值”字段右侧的“...”来编辑字符串集合。它会为您转换为 XML。
    【解决方案3】:

    在 App.config 中,

    <add key="YOURKEY" value="a,b,c"/>
    

    在 C# 中,

    字符串数组:

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

    列表:

     List<string> list = new List<string>(InFormOfStringArray);
    

    【讨论】:

    • 为什么不使用.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    猜你喜欢
    • 2013-06-05
    • 2022-06-15
    • 2018-09-09
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多