3

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?

Polynomial
  • 27,674
  • 12
  • 80
  • 107
user1482953
  • 181
  • 2
  • 2
  • 9

6 Answers6

2

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");
Mennan
  • 4,451
  • 13
  • 54
  • 86
Rohit Vyas
  • 1,949
  • 3
  • 19
  • 28
0

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");
}
Mennan
  • 4,451
  • 13
  • 54
  • 86
  • Thank you for your reply,but i am not understood where it should write in my application .i add this code in button_click event but giving me error.error is **The name 'ConfigurationUserLevel' does not exist in the current context** and many others – user1482953 Jul 25 '12 at 11:45
  • Did you add ConfigurationManager dll to your project ? – Mennan Jul 25 '12 at 12:08
  • thank you sir ,my connectiostring is updating ,but after closing application,and open again ,i see my connectiostring it remains same as before updating. – user1482953 Jul 26 '12 at 12:59
  • This example is for entries and not for the per the post. – Galactic Dec 13 '21 at 20:52
0

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.

rodrigocl
  • 111
  • 1
  • 3
0

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;
    }
Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
0
 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");
tenten
  • 1,276
  • 2
  • 26
  • 54
sarvjeet
  • 71
  • 1
  • 1
0

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");
Crypt32
  • 12,850
  • 2
  • 41
  • 70
sarvjeet
  • 71
  • 1
  • 1