Reputation: 9392
Is it possible to change the contents of web.config at run time?
Upvotes: 0
Views: 172
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
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
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