Reading & writing connection strings to an app.config file in C# 2.0

Ok after working on this for a bit this morning I am sharing my experience with the world. I needed to read and write some connection strings found in an app.config file I was using in a small C# .NET 2.0 application. First you must have a reference to the System.configuration dll in your project and use the System.Configuration namespace in any C# files you want to do this stuff in. This sample assumes you have your connection strings in a connectionString section of an app.config file.


Reading the connection string:

ConfigurationManager.ConnectionStrings["Connection Name"].ConnectionString




Writing the connection string:

// get the config file for this application
Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None );

// set the new values
config.ConnectionStrings.ConnectionStrings["Connection Name"].ConnectionString = "Connection String Value";

// save and refresh the config file
config.Save( ConfigurationSaveMode.Minimal );
ConfigurationManager.RefreshSection( "connectionStrings" );



For more info read the MSDN here.

Comments

akshay joshi said…
Thanks ! It helped me a lot
Anonymous said…
Thanks so much. It saves my life

Popular Posts