Mohammad Nadeem
Mohammad Nadeem

Reputation: 9392

Manipulating config file dynamically

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

Upvotes: 0

Views: 172

Answers (3)

Mohammad Nadeem
Mohammad Nadeem

Reputation: 9392

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();

Upvotes: 0

Mohammad Nadeem
Mohammad Nadeem

Reputation: 9392

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.

Upvotes: 0

Codesleuth
Codesleuth

Reputation: 10541

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).

Upvotes: 1

Related Questions