Saturday, April 17, 2010

change connection string in app.config programmatically/Runtime

Step 1 : Create a New  windows Forms application named configwrite

Step2 :  On Form put a button and a label

Step 3 : In code behind on click event of the button write the code
            shown below

 private void button1_Click(object sender, EventArgs e)
        {
Configuration c =        System.Configuration.ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
      c.ConnectionStrings.ConnectionStrings["connectionstring"].ConnectionString = "SERVER=changedservername; DATABASE=database; uid=username; pwd=password;";
            c.Save();
            label1.Text = "Connection String Changed";
      }

Note : The change in connectionstring is reflected in the
          configwrite\bin\debug\configwrite.exe.config  File

No comments:

Post a Comment