views:

9197

answers:

3

Would like to programmically change the connecton string for a database which utilizes the membership provider of asp.net within a windows application. The system.configuration namespace allows changes to the user settings, however, we would like to adjust a application setting? Does one need to write a class with utilizes XML to modify the class? Does one need to delete the current connections (can one select a connection to clear) and add a new one? Can one adjust the existing connection string?

+3  A: 

You can programatically open the configuration with using the System.configuration namespace:

Configuration myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

Then you can access the connection strings collection at:

myConfig.ConnectionStrings.ConnectionStrings

You can modify the collection however you want, and when done call .Save() on the configuration object.

Joseph Daigle
A: 

Use the ConnectionStringsSection class. The documentation even provides an example on how to create a new ConnectionString and have the framework save it to the config file without having to implement the whole XML shebang.

See here and browse down for an example.

Dave Van den Eynde
+6  A: 
// Get the application configuration file.
System.Configuration.Configuration config =
        ConfigurationManager.OpenExeConfiguration(
        ConfigurationUserLevel.None);

// Create a connection string element and
// save it to the configuration file.

// Create a connection string element.
ConnectionStringSettings csSettings =
        new ConnectionStringSettings("My Connection",
        "LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" +
        "Initial Catalog=aspnetdb", "System.Data.SqlClient");

// Get the connection strings section.
ConnectionStringsSection csSection =
    config.ConnectionStrings;

// Add the new element.
csSection.ConnectionStrings.Add(csSettings);

// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
dpollock