Scalable C # code to create an array from a configuration file

I have configuration values ​​as below

add key="Screen1" value ="Admin" add key="Screen2" value ="Log" 

In the future, new screens will be added. In C #, I need to create an array of strings with these screen names. How can we do this (bearing in mind that the code should work even if we add new screens)?

Note 1: I am looking for an approach that uses non- user configuration.

Note 2: I will have a maximum of 10 configuration items with a name starting with “Screen”. But I will have another 10,000 other configuration items.

LINK

-1
source share
3 answers
 ConfigurationManager.AppSettings.AllKeys .Where( key => key.StartsWith( "Screen" ) ) .Select( key => ConfigurationManager.AppSettings[key] ) 

If you have a lot of settings (for example, 10K, as indicated in the comments), you can take advantage of the fact that the AppSettings collection is optimized for key search. To do this, you will have to try "Screen1", "Screen2", "Screen3", etc. several times. And stop when no value is found:

 Enumerable.Range( 1, int.MaxValue ) .Select( i => ConfigurationManager.AppSettings[ "Screen" + i ] ) .TakeWhile( value => value != null ) 

This approach, however, is precisely the kind of “premature optimization” Mr. Knut warned us about. The configuration file simply does not have to contain many settings, period.

Another drawback: keep in mind that this approach assumes that there are no spaces in the numbering of the Screen settings. That is, if you have "Screen 1", "Screen 2" and "Screen 4", it will not record the latter. If you plan to have many of these parameters, it becomes very inconvenient to "change" all the numbers every time you add or remove settings.

+3
source

Create your own configuration section as described in the answer to this question .

Thus, you have full control over the contents in the configuration file and how it accesses the application.

Also see How to create custom configuration sections using ConfigurationSection on MSDN for a walkthrough.

+2
source

I'm not quite sure if you understand this problem, but you can list the settings and select everything that starts with "Screen".

See Enumerating Settings in .NET Applications .

0
source

All Articles