asp.net dynamically add connection string in web.config

783 views Asked by At

I have web application and windows application in same solution. I want to dynamically add connection string in web.config file. The connection string information give from windows application. How do i do this please help me.

My window app having:

WebForm1 wf = new WebForm1();
wf.add();

And my wep app having:

 public void add()
 {
      Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
      ConnectionStringsSection sec = (ConnectionStringsSection)config.GetSection("connectionStrings");
      sec.ConnectionStrings["DBCS"].ConnectionString = "Data Source=GKS_004-PC;Database=hello1;User ID=123;Password=123";
      config.Save();          
  }
1

There are 1 answers

0
CodeArtist On

I believe you address your problem in a way that may exist a different approach to solve your issue, however in order to do what you want you have two options. First you can read the file using the IO namespace and then parse it like XML using LINQ nodes and second you can use the Configuration class (System.Configuration and System.Web.Configuration namespaces).

//get the configuration file
Configuration config = WebConfigurationManager.OpenWebConfiguration("..."); //path to config

//get Configuration section
ConfigurationSection section = config.GetSection("..."); 

config.AppSettings.Settings.Add(Key, Value);
config.AppSettings.Settings.Remove(Key);

or this way, instead of using directly Configuration class

AppSettingsSection appsettings = (AppSettingsSection) config.GetSection("...");
appsettings.Settings.Add(key, Value);