C# Source Code: Reading and writing data in the App.Config file
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Reading and writing data in the App.Config file
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Friday, June 25, 2004
Hits:
2367
Category:
Serialisation (eg XML/SOAP)
Article:
The App.Config is designed as a readonly store for Application settings. Hence there is no direct support for dynamically updating the file (despite teasing you by offering a ConfigurationSettings.AppSettings.Add method which throws a read only exception). However, you may decide that you wish to update information in this file dynamically in which case you can use the two functions listed below. These routines demonstrate how to parse the XML settings in the App.Config file in order read and write them. You could of course use ConfigurationSettings.AppSettings.Get to return information from the config file. But since this information is cached you will not see the results of any updates that you make. using System.Configuration; using System.Xml; using System.Reflection; using System.IO; using System; namespace VBusers.AppConfigDemo { public class AppConfigTest { ///
/// Test routine ///
[STAThread] static void Main(string[] args) { AppConfiguration.SaveSetting("Test","TestValue"); Console.WriteLine(AppConfiguration.LoadSetting("Test","")); Console.ReadLine(); } } public class AppConfiguration { // Store the path to the app.config file (could make this dynamic if you wanted to) private static string _appConfigFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; //private static string _appConfigFile = Assembly.GetExecutingAssembly().Location + ".config"; ///
/// Returns a value from the app.config of the executing assembly. ///
///
The name of the setting to return. This setting should be stored in the app.config file eg: ///
///
///
///
///
/// ///
The value returned if no value is found ///
The value for the specified setting, or the defaultValue if the setting /// was not found
public static string LoadSetting(string setting, string defaultValue) { XmlNodeList settings; XmlElement node; XmlElement appSettingsNode; string query; if ( File.Exists(_appConfigFile) == false) { //Assembly does not have a app.config file return defaultValue; } //Load the app.config file XmlDocument doc = new XmlDocument(); doc.Load(_appConfigFile); //Find the
node query = "configuration/appSettings"; appSettingsNode = (XmlElement) doc.SelectSingleNode(query); if (appSettingsNode == null) { //App.config file does not contain an appSettings section return defaultValue; } //Find the setting query = "configuration/appSettings/add[@key='" + setting + "']"; settings = doc.SelectNodes(query); //Check to see if the node exists if (settings.Count >0) { //Node exists node = (XmlElement) settings[0]; //Return the value of the node return node.Attributes["value"].Value; } else { //The appSettings section does not contain the setting return defaultValue; } } ///
/// Sets a value in the app.config file of the executing assembly. ///
///
The name of the setting to store. ///
The value of the setting to save public static void SaveSetting(string setting, string settingValue) { XmlNodeList settings; XmlElement node; XmlElement appSettingsNode; string query; StreamWriter fileConfig; if ( File.Exists(_appConfigFile) == false) { //Create the app.config file and write the setting in it using(fileConfig = File.CreateText(_appConfigFile)) { fileConfig.WriteLine(@"
"); fileConfig.Close(); fileConfig = null; return; } } //Load the config file XmlDocument doc = new XmlDocument(); doc.Load(_appConfigFile); //Find the
node query = "configuration/appSettings"; appSettingsNode = (XmlElement) doc.SelectSingleNode(query); if (appSettingsNode == null) { //Add the app settings node and write the setting in it using(fileConfig = File.CreateText(_appConfigFile)) { fileConfig.WriteLine(@"
"); fileConfig.Close(); fileConfig = null; return; } } //Find the setting query = "configuration/appSettings/add[@key='" + setting + "']"; settings = doc.SelectNodes(query); //Check to see if the node already exists if (settings.Count >0) //Node exists node = (XmlElement) settings[0]; else { //Create the node
node = doc.CreateElement("add"); XmlAttribute attKey = doc.CreateAttribute("key"); attKey.Value = setting; node.Attributes.SetNamedItem(attKey); XmlAttribute attVal = doc.CreateAttribute("value"); node.Attributes.SetNamedItem(attVal); //Append the node appSettingsNode.AppendChild(node); } //Check to see if the value has changed if ( node.Attributes["value"].Value != settingValue ) { // Update the value attribute node.Attributes["value"].Value = settingValue; //Save the changes doc.Save(_appConfigFile); } doc = null; } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet