1

I want to change the app.setting connection string at the run time. I have some code to change it but i can't do this. there is no error appear during the run time. But there is no change during execution.

This is my partial code :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="Punch_Uploader.Properties.Settings.testConnectionString"
            connectionString="server=localhost;User Id=root;password=test123;database=test"
            providerName="MySql.Data.MySqlClient" />
        <add name="Punch_Uploader.Properties.Settings.testConnectionString1"
            connectionString="server=172.23.2.52;User Id=root;password=test123;database=test"
            providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
</configuration>

And:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Add(
    new ConnectionStringSettings("Punch_Uploader.Properties.Settings.testConnectionString2", 
        String.Format(
            "server={0};Port={1}; database={2};User Id={3};password={4};providerName={5}", 
            "172.23.2.32", "3306", "test", "root", "test123", "MySql.Data.MySqlClient")
        )
);
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings"); 

MessageBox.Show(ConfigurationManager
    .ConnectionStrings["Punch_Uploader.Properties.Settings.testConnectionString2"]
    .ConnectionString);

The above code is not working for me....

Please help me to fix this.

Noctis
  • 11,507
  • 3
  • 43
  • 82
Amulraj
  • 269
  • 4
  • 10
  • 21

4 Answers4

3
ConnectionStringSettings settings =
    ConfigurationManager.ConnectionStrings["Punch_Uploader.Properties.Settings.testConnectionString"];

string connectString = settings.ConnectionString;    

SqlConnectionStringBuilder builder =
        new SqlConnectionStringBuilder(connectString);

builder.DataSource = "172.23.2.52:3306";
builder.InitialCatalog = "test";
builder.UserID = "root";
builder.Password = "test123";

As mentioned in the comment to the previous answered I can confirm this method works as I've used it before to switch between different database environments.

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
0

Connection string is read only. To change connection string you need to manually saves changes back to the config file which will cause the application to restart.

Edit: quick search and I found this (might be helpful): connection string at runtime

Community
  • 1
  • 1
astro boy
  • 1,410
  • 1
  • 11
  • 16
  • This is absolutely not true. No changes can be made to the actual config file at run time however using the ConnectionStringBuilder classes mentioned in comment on the original post you can easily modify the connection string in memory. I have used this method in several apps to switch between development and test databases by manipulating the connection string to change the data source. – Jesse Carter Jun 08 '12 at 04:50
  • depends on what he wants to do. I thought he wanted to save the changes to the config file? – astro boy Jun 08 '12 at 05:30
  • To my knowledge you cannot save changes to the config file. You can only manipulate its values in memory. – Jesse Carter Jun 08 '12 at 05:33
0

Try this,

 Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
 ConnectionStringsSection section = webConfig.GetSection("connectionStrings") as            
                                              ConnectionStringsSection;
 if (section != null)
 {
   section.ConnectionStrings["NameTheCnStr"].ConnectionString = "New Connection string here";
   webConfig.Save();
  }
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
0

trying this Code

 private void UpdateConnectionString(string ConfigPath)
 {
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.Load(ConfigPath);
      XmlNode parentNode = xmlDocument.DocumentElement;
     if (parentNode.Name == "connectionStrings")
     {
        foreach (XmlNode childNode in parentNode.ChildNodes)
        {
           if (childNode.Name == "add" && childNode.Attributes["name"].Value=="Punch_Uploader.Properties.Settings.testConnectionString")
           {
             string sqlConnectionString =childNode.Attributes["connectionString"].Value;
             SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(sqlConnectionString);
             sqlBuilder.InitialCatalog = "yourDatabaseName";
             sqlBuilder.IntegratedSecurity = true;
             sqlBuilder.Password = "";

             //Change any other attributes using the sqlBuilder object
             childNode.Attributes["connectionString"].Value = sqlBuilder.ConnectionString;
           }
        }
      }
      xmlDocument.Save(ConfigPath);
  }

configPath is path of connection string from Web.config

string configPath  = ConfigurationManager.ConnectionStrings["Punch_Uploader.Properties.Settings.testConnectionString"].ConnectionString;
casperOne
  • 73,706
  • 19
  • 184
  • 253
dhiraj
  • 7
  • 1
  • 7
  • CofigPath is the Path of Web.config – dhiraj Jun 08 '12 at 08:57
  • now am using the below code. Its working fine when i am changing the IP. Properties.Settings.Default["testConnectionString"] = String.Format("server={0};Port={1}; database={2};User Id={3};password={4}", "172.23.2.32", "3306", "sunhrm", "root", "test123");. Now am change the database name means its not working. How can i fix this error – Amulraj Jun 08 '12 at 10:00