我想把一个一维字符串数组作为我的appSettings
的一个条目进行存储。我无法简单地使用,
或|
分隔元素,因为元素本身可能包含这些字符。
我考虑将数组存储为JSON
,然后使用JavaScriptSerializer
进行反序列化。
有没有更好的方法来实现这个需求?
(我的JSON
想法感觉有点不太正规)
我想把一个一维字符串数组作为我的appSettings
的一个条目进行存储。我无法简单地使用,
或|
分隔元素,因为元素本身可能包含这些字符。
我考虑将数组存储为JSON
,然后使用JavaScriptSerializer
进行反序列化。
有没有更好的方法来实现这个需求?
(我的JSON
想法感觉有点不太正规)
您可以使用AppSettings和System.Collections.Specialized.StringCollection
。
var myStringCollection = Properties.Settings.Default.MyCollection;
foreach (String value in myStringCollection)
{
// do something
}
每个值都用新行分隔。
这是一张截图(德国IDE,但仍可能有帮助)int[] ints = new int[strings.Count]; for(int i = 0; i < strings.Count; i++) ints[i] = int.Parse(strings[i]);
- Tim SchmeltermyStringCollection
与myCollection
不同。 - Jesse ChisholmASP.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>>();
对于整数,我发现以下方法更快。
首先,在您的 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();
对于字符串,很容易,只需将以下内容添加到您的web.config
文件中:
<add key="myStringArray" value="fred,Jim,Alan" />
然后您可以按如下方式将值检索到数组中:
var myArray = ConfigurationManager.AppSettings["myStringArray"].Split(',');
[...]
来包围 "MyStringArray"
,而不是使用 (...)
,或者我漏掉了什么? - WAFvar myArray = ConfigurationManager.AppSettings["MyStringArray"].Split(',');
- dev<configSections>
<section name="configSection" type="YourApp.ConfigSection, YourApp"/>
</configSections>
<configSection xmlns="urn:YourApp">
<stringItems>
<item value="String Value"/>
</stringItems>
</configSection>
使用 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[]>();