在appSettings中存储字符串数组?

34

我想把一个一维字符串数组作为我的appSettings的一个条目进行存储。我无法简单地使用,|分隔元素,因为元素本身可能包含这些字符。

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

有没有更好的方法来实现这个需求?

(我的JSON想法感觉有点不太正规)


1
如果你选择这条路线,我推荐使用Newtonsoft JSON库。 - user166390
6个回答

27

您可以使用AppSettings和System.Collections.Specialized.StringCollection

var myStringCollection = Properties.Settings.Default.MyCollection;
foreach (String value in myStringCollection)
{ 
    // do something
}
每个值都用新行分隔。 这是一张截图(德国IDE,但仍可能有帮助)enter image description here

这个能用于整数吗? - akd
@akdurmus:只有在将它们转换为整数时才能这样做:int[] ints = new int[strings.Count]; for(int i = 0; i < strings.Count; i++) ints[i] = int.Parse(strings[i]); - Tim Schmelter
我似乎找到了更好的答案并在下面发布了。谢谢@Tim - akd
代码中的一个打字错误:myStringCollectionmyCollection不同。 - Jesse Chisholm

16

ASP.Net Core支持绑定字符串或对象列表。

对于上述字符串,可以通过AsEnumerable()进行检索。

或者通过Get<List<MyObject>>()检索对象列表。下面是示例。

appsettings.json:

{
 ...
   "my_section": {
     "objs": [
       {
         "id": "2",
         "name": "Object 1"
       },
       {
         "id": "2",
         "name": "Object 2"
       }
     ]
   }
 ...
}

代表对象的类

public class MyObject
{
    public string Id { get; set; }
    public string Name { get; set; }
}

appsettings.json 中检索代码

Configuration.GetSection("my_section:objs").Get<List<MyObject>>();

1
谢谢!这个对我有用。之前尝试了简单的getvalue,但是它为空。 - Shahab Uddin
这非常有帮助,@Rodrigo。 如果要挑选出一个具有特定 id 的对象,比如那个具有 "id":"2" 的对象,语法会是什么样子? - David Mays

12

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

首先,在您的 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();

12

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

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

然后您可以按如下方式将值检索到数组中:

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

你是不是想用[...]来包围 "MyStringArray",而不是使用 (...),或者我漏掉了什么? - WAF
2
应该是:var myArray = ConfigurationManager.AppSettings["MyStringArray"].Split(','); - dev

7
您也可以考虑使用自定义配置部分/集合来实现此目的。以下是一个示例:
<configSections>
    <section name="configSection" type="YourApp.ConfigSection, YourApp"/>
</configSections>

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

你还可以使用这个优秀的Visual Studio插件,它允许你图形化设计.NET配置节,并自动生成所有必需的代码和模式定义(XSD)。插件链接:https://github.com/hybridview/ConfigurationSectionDesigner

7
这可能是您正在寻找的内容:

使用 appsettings 存储 NoLongerMaintained 关键字和字符串数组。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "NoLongerMaintained": ["BCD",
    "DDP",
    "DHF",
    "DHW",
    "DSG",
    "DTH",
    "SCH"]
}

您可以使用以下方式以字符串数组 string[] 的形式检索它

var NoLongerMaintained = _config.GetSection("NoLongerMaintained").Get<string[]>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接