Is it possible to change the contents of web.config at run time?
            Asked
            
        
        
            Active
            
        
            Viewed 158 times
        
    0
            
            
        - 
                    1possible duplicate of [How do you modify the web.config appSettings at runtime?](http://stackoverflow.com/questions/719928/how-do-you-modify-the-web-config-appsettings-at-runtime) – M4N Sep 15 '10 at 08:43
 
3 Answers
1
            
            
        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
        
- 10,321
 - 8
 - 51
 - 71
 
0
            
            
        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.
        Mohammad Nadeem
        
- 9,134
 - 14
 - 56
 - 82
 
0
            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();
        Mohammad Nadeem
        
- 9,134
 - 14
 - 56
 - 82