在appSettings中存储字符串数组?

Gre*_*reg 26 .net asp.net app-config web-config asp.net-4.0

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

我正在考虑存储数组,JSON然后使用它反序列化它JavaScriptSerializer.

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

(我的JSON想法有点像hacky)

Tim*_*ter 24

你可以使用AppSettings System.Collections.Specialized.StringCollection.

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

每个值由一个新行分隔.

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

在此输入图像描述


小智 16

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

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

或者通过 的对象列表Get<List<MyObject>>()。示例如下。

appsettings.json:

{
 ...
   "my_section": {
     "objs": [
       {
         "id": "2",
         "name": "Object 1"
       },
       {
         "id": "2",
         "name": "Object 2"
       }
     ]
   }
 ...
}
Run Code Online (Sandbox Code Playgroud)

代表对象的类

public class MyObject
{
    public string Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

从中检索的代码appsettings.json

Configuration.GetSection("my_section:objs").Get<List<MyObject>>();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!这对我有用。以前尝试过简单的 getvalue 并且它是 null (2认同)

akd*_*akd 10

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

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

<add key="myIntArray" value="1,2,3,4" />
Run Code Online (Sandbox Code Playgroud)

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

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


小智 9

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

<add key="myStringArray" value="fred,Jim,Alan" />
Run Code Online (Sandbox Code Playgroud)

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

var myArray = ConfigurationManager.AppSettings["myStringArray"].Split(',');
Run Code Online (Sandbox Code Playgroud)

  • 应该是var myArray = ConfigurationManager.AppSettings [“ MyStringArray”]。Split(',');` (2认同)

Rob*_*Rob 7

这可能就是您正在寻找的:

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

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "NoLongerMaintained": ["BCD",
    "DDP",
    "DHF",
    "DHW",
    "DSG",
    "DTH",
    "SCH"]
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用数组 string[] 来检索它

var NoLongerMaintained = _config.GetSection("NoLongerMaintained").Get<string[]>();
Run Code Online (Sandbox Code Playgroud)


Kib*_*ria 5

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

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

<configSection xmlns="urn:YourApp">
  <stringItems>
    <item value="String Value"/>
  </stringItems>
</configSection>
Run Code Online (Sandbox Code Playgroud)

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