简体   繁体   中英

update connectionstring in app.config file at run time in C#

I have created an application and in that application am going to insert, update and delete data operation in database

I have also created a form for connection settings, where user can update server name, datatbase and user id and password. I have stored my connection string in app.config file.

My problem is, how can I update connection string in app.config file at run time?

You can try this:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("MyConnectionString",String.Format("DataSource={0};InitialCatalog={1};IntegratedSecurity={2}","testing", "testing2", "Testing6")));
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

You can try this:

private void changeValue(String KeyName, String KeyValue)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// Update the setting.
config.AppSettings.Settings[KeyName].Value = KeyValue;

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

// Force a reload of the changed section.
ConfigurationManager.RefreshSection("appSettings");
}

I believe that your App.Config is not updating because it is using the vshost. I had this issue today, and I tried the solutions of this post, but running on VisualStudio, so the file was the same. Outside VS it worked as a charm.

App.cofig Code

      <?xml version="1.0" encoding="utf-8"?>
        <configuration>
     <configSections>
            <section name="dataConfiguration"type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral,        PublicKeyToken=b03f5f7f11d50a3a" />
     </configSections>
    <connectionStrings>
  <add name="DbDatabase" providerName="System.Data.SqlClient" connectionString=""/>
</connectionStrings>

C# Code

   public void updateConfigFile(string con)
    {
        //updating config file
        XmlDocument XmlDoc = new XmlDocument();
        //Loading the Config file
        XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
       // XmlDoc.Load("App.config");
        foreach (XmlElement xElement in XmlDoc.DocumentElement)
        {
            if (xElement.Name == "connectionStrings")
            {
                //setting the coonection string
                xElement.FirstChild.Attributes[2].Value = con;
            }
        }
        //writing the connection string in config file
        XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        //XmlDoc.Save("App.config");
    }



 private void btn_Connect_Click(object sender, EventArgs e)
    {
        StringBuilder Con = new StringBuilder("Data Source=");
        Con.Append(txt_ServerName.Text);
        Con.Append(";Initial Catalog=");
        Con.Append(txt_DatabaseName.Text);
        if (String.IsNullOrEmpty(txt_UserId.Text) &&String.IsNullOrEmpty(txt_Password.Text))
            Con.Append(";Integrated Security=true;");
        else
        {
            Con.Append(";User Id=");
            Con.Append(txt_UserId.Text);
            Con.Append(";Password=");
            Con.Append(txt_Password.Text);
        }
        string strCon = Con.ToString();
        updateConfigFile(strCon);

        DatabaseTableDA da = new DatabaseTableDA();
        tableList = da.Select_Tables();
        this.lstTables.DataSource = tableList;
    }
 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
 connectionStringsSection.ConnectionStrings["ClientCN"].ConnectionString = "server=localhost;user=root;port=3306;password=abc";
 config.Save();
  ConfigurationManager.RefreshSection("connectionStrings");

try this:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["ClientCN"].ConnectionString = "server=localhost;user=root;port=3306;password=abc";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM