Wednesday, March 5, 2008

How to Add User defined tags in the Webconfig file and Write and Retrive the values

using System.Xml; // Must Include

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="AdminSettings" type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
.
.
.
</configSections>
.
.
</configuration>
//Your WebConfig Content Something like this
//User defined tags should have to mention like the above section
---------------------------------
<AdminSettings>
<add key="AdminUserName" value="professionals" />
<add key="AdminPassword" value="buzz" />
</AdminSettings>
---------------------------------
protected void BtnWriteConfig_Click(object sender, EventArgs e)
{
string Path=Server.MapPath("~/web.config");
XmlDocument xDoc = new XmlDocument();
XmlNodeList nodeList;
XmlNodeList nodeAppSettings;
xDoc.Load(Path);
nodeList = xDoc.GetElementsByTagName("AdminSettings");
nodeAppSettings = nodeList[0].ChildNodes;
for (int i = 0; i < nodeAppSettings.Count; i++)
{
XmlAttributeCollection xmlAttCollection = nodeAppSettings[i].Attributes;
if (xmlAttCollection[0].InnerXml == "AdminUserName")
{
xmlAttCollection[1].InnerXml = USR.ToString();
}
if (xmlAttCollection[0].InnerXml == "AdminPassword")
{
xmlAttCollection[1].InnerXml = PWD.ToString();
}
}
xDoc.Save(Path);
}
---------------------------------
//Getting userdefined tag values
string Uname = ((System.Collections.Specialized.NameValueCollection)ConfigurationManager.GetSection("AdminSettings"))["AdminUserName"] + "";
string Pwd = ((System.Collections.Specialized.NameValueCollection)ConfigurationManager.GetSection("AdminSettings"))["AdminPassword"] + "";

No comments:

 
Feedback Form