¿Almacenar Matriz De Cadenas En AppSettings?
Me gustaría almacenar una matriz de cadena unidimensional como una entrada en mi appSettings
. No puedo simplemente separar elementos con ,
o |
porque los elementos mismos podrían contener esos caracteres.
Estaba pensando en almacenar el array como JSON
y luego deserializarlo usando el JavaScriptSerializer
.
¿Hay una manera "correcta" / mejor de hacer esto?
(Mi JSON
idea se siente un poco hacky)
4 answers
Podría usar las AppSettings con un System.Collections.Specialized.StringCollection
.
var myStringCollection = Properties.Settings.Default.MyCollection;
foreach (String value in myCollection)
{
// do something
}
Cada valor está separado por una nueva línea.
Aquí hay una captura de pantalla (IDE alemán, pero podría ser útil de todos modos)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-02 18:24:08
Para los enteros encontré la siguiente manera más rápida.
En primer lugar, cree una clave AppSettings con valores enteros separados por comas en su aplicación.config.
<add key="myIntArray" value="1,2,3,4" />
Luego divida y convierta los valores en una matriz int usando LINQ
int[] myIntArray = ConfigurationManager.AppSettings["myIntArray"].Split(',').Select(n => Convert.ToInt32(n)).ToArray();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-15 10:54:28
Para cadenas es fácil, simplemente agregue lo siguiente a su archivo web.config
:
<add key="myStringArray" value="fred,Jim,Alan" />
Y luego puede recuperar el valor en una matriz de la siguiente manera:
var myArray = ConfigurationManager.AppSettings("myStringArray").Split(',');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-10 08:01:11
También puede considerar usar la sección/Colección de configuración personalizada para este propósito. He aquí una muestra:
<configSections>
<section name="configSection" type="YourApp.ConfigSection, YourApp"/>
</configSections>
<configSection xmlns="urn:YourApp">
<stringItems>
<item value="String Value"/>
</stringItems>
</configSection>
También puede comprobar este excelente complemento Visual Studio que le permite diseñar gráficamente Secciones de configuración de.NET y genera automáticamente todo el código requerido y una definición de esquema (XSD) para ellas.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-06 13:17:09