Store String Array In appSettings?

喜夏-厌秋 提交于 2019-11-26 09:47:41

问题


I\'d like to store a one dimensional string array as an entry in my appSettings. I can\'t simply separate elements with , or | because the elements themselves could contain those characters.

I was thinking of storing the array as JSON then deserializing it using the JavaScriptSerializer.

Is there a \"right\" / better way to do this?

(My JSON idea feels kinda hacky)


回答1:


You could use the AppSettings with a System.Collections.Specialized.StringCollection.

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

Each value is separated by a new line.

Here's a screenshot (german IDE but it might be helpful anyway)




回答2:


For integers I found the following way quicker.

First of all create a appSettings key with integer values separated by commas in your app.config.

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

Then split and convert the values into int array by using LINQ

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



回答3:


For strings it is easy, simply add the following to your web.config file:

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

and then you can retrieve the value into an array as follows:

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



回答4:


You may also consider using custom configuration section/Collection for this purpose. Here is a sample:

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

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

You can also check on this excellent Visual Studio add-in that allows you to graphically design .NET Configuration Sections and automatically generates all the required code and a schema definition (XSD) for them.



来源:https://stackoverflow.com/questions/10419116/store-string-array-in-appsettings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!