开发者

Manipulating config file dynamically

Is it possible to change the contents of web.config at 开发者_如何学JAVArun time?


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜