Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

How i overwrite connection string in web config ?

i used below code
C#
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("MyConnectionString") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
section = (ConnectionStringsSection)config.GetSection("connectionStrings");
if (section != null)
{
   section.ConnectionStrings["connectionStrings"].ConnectionString = "Data Source=" + Server + ";Initial Catalog=" + Name + ";User ID=" + Username + ";Password=" + Password + ";Pooling=true;Min Pool Size=5;Max Pool Size=60;Connect Timeout=60"; 
   config.Save();
}


But the code inside the 'if condition' throw an object reference error..plz suggest a solution for this issue..


section.ConnectionStrings["connectionStrings"].ConnectionString is show null in add watch
Posted
Updated 13-Oct-14 23:25pm
v3

1 solution

The "connectionStrings" is the name of the section not the connection string name.

C#
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=" + Server + ";Initial Catalog=" + Name + ";User ID=" + Username + ";Password=" + Password + ";Pooling=true;Min Pool Size=5;Max Pool Size=60;Connect Timeout=60";
configuration.Save();


I have copied solution from this link
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900