【问题标题】:Store String Array In appSettings?在 appSettings 中存储字符串数组?
【发布时间】:2012-05-12 05:51:39
【问题描述】:

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

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

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

(我的JSON 想法有点老套)

【问题讨论】:

  • 我推荐 Newtonsoft JSON 的东西,如果你走那条路...

标签: asp.net .net web-config app-config asp.net-4.0


【解决方案1】:

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

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

每个值都由一个新行分隔。

这是一个屏幕截图(德语 IDE,但无论如何它可能会有所帮助)

【讨论】:

  • 这可以用于整数吗?
  • @akdurmus:仅当您将它们转换为 int 时:int[] ints = new int[strings.Count]; for(int i = 0; i < strings.Count; i++) ints[i] = int.Parse(strings[i]);
  • 我似乎找到了更好的答案并发布在下面。谢谢@蒂姆
  • 代码中的错字:myStringCollection 与 myCollection。
【解决方案2】:

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

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

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

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

【讨论】:

  • 您是指[...] 周围的"MyStringArray",而不是(...),还是我遗漏了什么?
  • 应该是var myArray = ConfigurationManager.AppSettings["MyStringArray"].Split(',');
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

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

    对于上面提到的字符串,可以通过AsEnumerable()检索。

    或通过Get&lt;List&lt;MyObject&gt;&gt;() 列出对象列表。示例如下。

    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>>();
    

    【讨论】:

    • 谢谢!这对我有用。以前尝试过简单的getvalue,它是null
    【解决方案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)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 2016-03-17
      • 1970-01-01
      相关资源
      最近更新 更多