tags:

views:

43

answers:

3

Is it possible to change the contents of web.config at run time?

+1  A: 

Yes, it is.

The safe way is to write to appSettings: Writing to Your .NET Application's Config File
But you can also hack it (don't do this).

Codesleuth
A: 

I have tried the following code to update the web.config file at runtime.

Lets say web.config has a key like this

<connectionStrings>
    <add name="conkey" connectionString="old value" />
</connectionStrings>

And here is the C# code to update the web.config file.

 string path = Server.MapPath("Web.config");
             string newConnectionString = "updated value"; // Updated Value

            XmlDocument xDoc = new XmlDocument(); 
            xDoc.Load(path);

            XmlNodeList nodeList = xDoc.GetElementsByTagName("connectionStrings");

            XmlNodeList nodeconnectionStrings = nodeList[0].ChildNodes;

            XmlAttributeCollection xmlAttCollection = nodeconnectionStrings[0].Attributes;

            xmlAttCollection[1].InnerXml = newConnectionString; // for value attribute

            xDoc.Save(path); // saves the web.config file  

This code worked for me. However it is recommended not to do this.

Nadeem
A: 

Another way to do so by using WebConfigurationManager class.

Configuration cfg = WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringSettings consettings = cfg.ConnectionStrings.ConnectionStrings["conkey"];
consettings.ConnectionString = "updated value";           
cfg.Save();
Nadeem