tags:

views:

54

answers:

2

How to Load & Save to values in app.config file ?

For example: to save & to load Connection string

+1  A: 

You use the ConfigurationManager class, which has a Save method. That documentation page has a comprehensive example of loading custom configuration sections and saving values.

womp
A: 

Try this

public static string ConnectionString
{
        get
        {
            try
            {
                return ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ConnectionString;
            }
            catch
            {
                return "";
            }
        }
        set
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings["YourConnectionStringName "].ConnectionString = value;
            config.Save(ConfigurationSaveMode.Minimal, true);
            //refresh so that you can use the updates value directly without the need to restart the application
            System.Configuration.ConfigurationManager.RefreshSection("connectionStrings");
        }
    }
Sameh Serag
-1: for hiding the exception. How will you ever fix any exception that occurs in that block? You'll never know that you _had_ an exception!
John Saunders
Thanks for your note :) You are right about I will not know the exact type of the thrown exception. But I copied the code from another project at which the type of exception is not as important as existence or nonexistence of the connection string (notice that I returned an empty string in this case, which in turn will fail the connection to the database, and that is what I needed there).Anyway, thanks for the tip :)
Sameh Serag
That exception (a NullReferenceException) could easily be avoided simply by checking if the return from ConnectionStrings["..."] is null before accessing the ConnectionString property. If this were called frequently, that exception could have major performance implications.
Josh Einstein