C # app.config in winform

I usually use a text file as a config. But this time I would like to use app.config to associate the file name (key) with the name (value) and make the names available in the combo box

<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="Scenario1.doc" value="Hybrid1"/> <add key="Scenario2.doc" value="Hybrid2"/> <add key="Scenario3.doc" value="Hybrid3"/> </appSettings> </configuration> 

will it work? how to get data?

+6
source share
2 answers

Straight from docs :

 // Get the AppSettings section. // This function uses the AppSettings property // to read the appSettings configuration // section. public static void ReadAppSettings() { try { // Get the AppSettings section. NameValueCollection appSettings = ConfigurationManager.AppSettings; // Get the AppSettings section elements. Console.WriteLine(); Console.WriteLine("Using AppSettings property."); Console.WriteLine("Application settings:"); if (appSettings.Count == 0) { Console.WriteLine("[ReadAppSettings: {0}]", "AppSettings is empty Use GetSection command first."); } for (int i = 0; i < appSettings.Count; i++) { Console.WriteLine("#{0} Key: {1} Value: {2}", i, appSettings.GetKey(i), appSettings[i]); } } catch (ConfigurationErrorsException e) { Console.WriteLine("[ReadAppSettings: {0}]", e.ToString()); } } 

So, if you want to access the Scenario1.doc setting, you should do the following:

var value = ConfigurationManager.AppSettings["Scenario1.doc"];

Edit:

As Gabriel GM said in the comments, you will need to add a link to System.Configuration .

+11
source

Application settings in app.config are designed to store application / environment settings that are not intended to store data that are tied to the user interface.

If you cannot save to config due to weird business requests, I'd rather stick with one setting

 <add key="FileDropDown" value="File1-Value|File2-Value" /> 

and write C # code to get this ConfigurationManager.AppSettings["FileDropDown"] parameter, and do some line ConfigurationManager.AppSettings["FileDropDown"] ('|') and ('-') to create a kvp collection and bind it to the user interface.

0
source

Source: https://habr.com/ru/post/926965/


All Articles