How to change any property of Config File in Code



Here I have kept a connection string in web.config file and the below code will help you out to modify the connection string property. Like this you can modify other section in your Web.config file.Paste the below code on the required method.


string constr = ConfigurationManager.ConnectionStrings[0].ConnectionString;

            Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
            ConnectionStringsSection conSetSection = (ConnectionStringsSection)objConfig.GetSection("connectionStrings");
            if (conSetSection != null)
            {
                conSetSection.ConnectionStrings[0].ConnectionString = "Not found";
                objConfig.Save();
           
            }


So Finally connection string property will change as "Not Found" where as it was earlier "Data Source=(Local);Initial Catalog=xyz; integrated security=true;"

No comments:

Post a Comment