Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

How to Make Your .NET Windows Forms Configuration Files Dynamic  : Page 2

Although Windows Forms configuration files are read-only within the framework, they become dynamic XML databases when you create this AppSettingsManager class.


advertisement
Configuration File Name and Location
Whenever you store data outside of your application, there's always a danger that the data might not be available, and you also face the problem of finding the file. You can't simply hard-code a path, because you may not know exactly where a user installed your application. The framework simplifies the problem by restricting the name and location of configuration files using two rules:

  1. Windows Forms configuration files must be named exactly the same as the executable file, including the .exe extension, followed by .config. For example, if your executable file is myApp.exe, the configuration file must be named myApp.exe.config.
  2. The configuration file must reside in the same folder as the executable file.
These restrictions make finding the configuration file for a Windows Form application a one-line operation. Here's how to obtain the configuration file name for a Windows Forms application:

Dim configFile As String = _ Application.ExecutablePath & ".config"

The Application.ExecutablePath property returns the full path to the exe file for the running application. Appending .config gives you the configuration file name that matches the configuration file name and location rules. Just because you have the proper file name doesn't mean that the file exists. Use the File or FileInfo classes' Exists method before attempting to read or modify the file.

Modifying Configuration Values
After obtaining the file location, you can add, remove, or modify <appSettings> (or any other section's) values using straightforward XML DOM methods. For example, suppose you have a configuration file containing the following three key/value pairs.

<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="v1" value="Value 1" /> <add key="v2" value="Value 2" /> <add key="v3" value="Value 3" /> </appSettings> </configuration>

You can create additional settings by reading the file, obtaining an XmlElement object reference for the element, creating a new child element, setting its attributes and values, and then appending the new child element to the element's ChildNodes collection.

The following code shows the entire process to create a new element containing a key and value pair to the element for the configuration file shown earlier.



Dim s As String = "" s = Me.getConfigValue("v4") If s Is Nothing Then Console.WriteLine( _ "Adding new configuration value.") ' Get the configuration file name Dim configFile As String = Application.ExecutablePath + ".config" ' create a new XmlDocument object Dim Xml As XmlDocument = New XmlDocument() ' load the configuration file Xml.Load(configFile) ' get a reference to the <appSettings> section Dim appSettingsElement As _ XmlNode = Xml.SelectSingleNode( _ "//configuration/appSettings") ' create a new <add> element Dim newElement As XmlElement = _ Xml.CreateElement("add") ' set its attributes newElement.SetAttribute("key", "v4") newElement.SetAttribute( _ "value", "Value 4") ' append it to the <appSettings> section appSettingsElement.AppendChild(newElement) Xml.Save(configFile) ' changes are not live until ' the app is restarted--the following ' line prints nothing Console.WriteLine(Me.getConfigValue("v4")) Else Console.WriteLine("Configuration value " & _ """v4"" already exists." & _ " Value: " & s) End If Private Function getConfigValue( _ ByVal key As String) As String Return System.Configuration. _ ConfigurationSettings.AppSettings.Get(key) End Function

The sample code (download from the link in the left column) contains a form where you can test the preceding code. Click the "Simple Example" button to see the configuration file before and after running the code (see Figure 1).

Figure 1
Figure 1: Clicking the "Simple Example" button on the sample form adds an entry to the configuration file using the System.Xml classes and shows the configuration file before and after clicking the button.
The first time you run the application, clicking the Simple Example button creates a new "v4" entry for each click, even though the code checks to see if the "v4" key already exists! However, if you close the application and then restart it, clicking the Simple Example button doesn't do anything except display a message box that the setting already exists. That seems odd. Why doesn't the check at the beginning of the code find the entry the second time you click the button? The answer is that because the call to getConfigValue() uses the System.Configuration.Configuration.AppSettings class to retrieve the value—and that class doesn't recognize changes made to the configuration file while the application is running. The second time you run the application though, the framework reads the altered configuration file, the getConfigValue() call returns the "v4" setting value, and the class properly displays the message box.

But My Changes Aren't Live!
As you can see by running the code in the preceding section, you can easily alter the contents of a configuration file programmatically, but the built-in configuration classes don't recognize any changes you make to the configuration file until the next time you launch the application. That's no good.

What you need is to be able to both modify the file and use the modifications within a single application instance. To do that, you have to compromise a bit. The key is to avoid using the built-in configuration classes to access your <appSettings> data; instead, create a class to manage them for you. The sample SettingsManager project contains a class named AppSettingsManager that both reads and writes <appSettings> values dynamically. You use the AppSettingsManager class to read and modify <appSettings> items rather than the built-in classes. When the class terminates, it automatically saves any changes you've made to the configuration file.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap