如何将字符串数组写入应用程序config(c#)文件,以及如何将这些数组值读取到我们的.cs文件中.

如何将字符串数组写入应用程序config(c#)文件,以及如何将这些数组值读取到我们的.cs文件中.

问题描述:

大家好,

如何将字符串数组写入应用程序config(c#)文件,以及如何将这些数组值读取到我们的.cs文件中.

在此先感谢...

hi all,

How to write string array into app config(c#) file and how to read those array values into our .cs file.

Thanks in advance...

最简单的方法可能是使用分号(例如逗号)输入键的值.使用字符串的拆分"功能拆分值,就可以得到数组.根据所需数组的类型,您需要进行转换.

配置文件
probably the easiest way to do this is to enter the value of the key with a delimeter (eg a comma). Use the string''s Split function to split the values and there you have your array. Depending on the type of your needed array, you''ll need to convert.

config file
<add key="myarray" value="1,5,6,8,9" />



背后的代码



Code behind

string myarrayvalue = ConfigurationManager.AppSettings["myarray"];
string [] str_array = myarrayvalue.Split(new string[]{","}, StringSplitOptions.RemoveEmptyValues);

//if needed as eg. an integer.
int [] myintarray = new int[str_array.Length];
for(int i = 0; i < str_array.Length; i++){
  int output;
  if(int.TryParse(str_array[i], out output){
    myintarray[i] = output;
  }
  else{
    myintarray[i] = -1;
  }
}



这是一个非常基本的问题,请从一本好书开始.



This is a pretty basic question, please start out with a good book.


有一个现有的类可以做到这一点: ^ ]

ConfigurationConverterClass描述 [
There is an existing class that can do just that: CommaDelimitedStringCollectionConverter Class[^]

There is an example as part of the ConfigurationConverterClass description[^]