VS2005 C# Programmatically change connection strin

2019-01-12 03:29发布

问题:

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?

回答1:

Had to do this exact thing. This is the code that worked for me:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["Blah"].ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");


回答2:

// 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);


回答3:

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.



回答4:

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.