在appSettings中存储字符串数组?

问题描述 投票:25回答:4

我想在我的appSettings中存储一维字符串数组作为条目。我不能简单地用,|分隔元素,因为元素本身可以包含那些字符。

我正在考虑将数组存储为JSON,然后使用JavaScriptSerializer对其进行反序列化。

有没有“正确”/更好的方法来做到这一点?

(我的JSON想法有点像hacky)

asp.net .net web-config app-config asp.net-4.0
4个回答
23
投票

您可以将AppSettings与System.Collections.Specialized.StringCollection一起使用。

var myStringCollection = Properties.Settings.Default.MyCollection;
foreach (String value in myCollection)
{ 
    // do something
}

每个值由一个新行分隔。

这是一个截图(德语IDE,但它可能会有所帮助)


10
投票

对于整数,我发现以下方法更快。

首先在app.config中创建一个appSettings键,其中的整数值用逗号分隔。

<add key="myIntArray" value="1,2,3,4" />

然后使用LINQ将值拆分并转换为int数组

int[] myIntArray =  ConfigurationManager.AppSettings["myIntArray"].Split(',').Select(n => Convert.ToInt32(n)).ToArray();

9
投票

对于字符串,它很简单,只需将以下内容添加到web.config文件中:

<add key="myStringArray" value="fred,Jim,Alan" />

然后您可以将值检索到数组中,如下所示:

var myArray = ConfigurationManager.AppSettings["myStringArray"].Split(',');

5
投票

您也可以考虑使用自定义配置部分/集合来实现此目的。这是一个示例:

<configSections>
    <section name="configSection" type="YourApp.ConfigSection, YourApp"/>
</configSections>

<configSection xmlns="urn:YourApp">
  <stringItems>
    <item value="String Value"/>
  </stringItems>
</configSection>

您还可以查看这个优秀的Visual Studio add-in,它允许您以图形方式设计.NET配置节,并自动为它们生成所有必需的代码和模式定义(XSD)。

© www.soinside.com 2019 - 2024. All rights reserved.