spicy.net: Writing in Web.config file dynamically...

spicy.net

Sunday, July 02, 2006

Writing in Web.config file dynamically...

Introduction:
Web.config allows the developers to change the configuration of the application without having to build the application. Its not a good idea to write to the configuration file dynamically as it will restart the application. But sometimes we need the feature to dynamically write to the config file. This can be the case when you allow the users to personalize the connection string. In this article we will see how we can dynamically write the connection string to the Web.config file.
What are we going to write?
Since, we are changing the connection string dynamically we will need to write the key as well as the database name to the configuration file.
C# Code:
We will need to include the namespace System.xml. All we are doing is setting the tag in web.config file.
private void SetConfigSettings()
{
string path = Server.MapPath("Web.config");
string newConnectionString = @"Server=local;Database="+txtDatabaseName.Text+";Trusted_Connection=true";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
XmlNodeList nodeList = xDoc.GetElementsByTagName("appSettings");
XmlNodeList nodeAppSettings = nodeList[0].ChildNodes;
XmlAttributeCollection xmlAttCollection = nodeAppSettings[0].Attributes;
xmlAttCollection[0].InnerXml = txtKey.Text; // for key attribute
xmlAttCollection[1].InnerXml = newConnectionString; // for value attribute
xDoc.Save(path); // saves the web.config file
}
Conculsion:
Although it's not a good idea to write to the configuration file dynamically but sometimes depending on the situation we might have to use that approach.

0 Comments:

Post a Comment

<< Home