c# – accessig application configuration file using ConfigurationManager

By | 27. March 2017

Using configuration file is pretty straightforward. First  add to your application references Assembly System.Configuration. ConfigurationManager provides access to configuration files for client applications,

It makes sense to encapsulate configuration settings read and write to special methods.


        public static string ReadSetting(string key, string defaultValue = "Not Found")
            var appSettings = ConfigurationManager.AppSettings;
            string result = appSettings[key] ?? defaultValue;
            return result;

        public static void AddUpdateAppSettings(string key, string value)
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;
            if (settings[key] == null)
                settings.Add(key, value);
                settings[key].Value = value;

To add or update use AddUpdateAppSettings:

AddUpdateAppSettings("mysql_host", "localhost");
AddUpdateAppSettings("mysql_port", "3306");
AddUpdateAppSettings("mysql_user", "root");
AddUpdateAppSettings("mysql_password", "");
AddUpdateAppSettings("mysql_db", "mydb");

For read use ReadSetting. In this sample we provide also default values so in case of missing configuration the application still works in development environment:

string mysql_host = ReadSetting("mysql_host", "localhost");
string mysql_user = ReadSetting("mysql_user", "root");
string mysql_password = ReadSetting("mysql_password", "");
string mysql_db = ReadSetting("mysql_db", "mydb");
int mysql_port;
     mysql_port = Convert.ToInt32(ReadSetting("mysql_port", "3306"));
catch (Exception)
     mysql_port = 3306;

Keep in mind that if you run your application from Visual Studio the configuration file accessed and changed is YourApplicationName.vshost.exe.Config residing in \bin\Debug\ directory.

Both YourApplicationName.vshost.exe.Config and YourApplicationName.exe.config are copied do this directory from App.config usually located in project root directory. So if you want to have permanent configuration settings the App.config file must be amended.


Leave a Reply