|
Master .NET Configuration Files
Learn how to load and save configuration files using Visual Studio.
by Francesco Balena
January 7, 2005
Technology Toolbox: VB.NET, C#
You can simplify application deployment and customization greatly by keeping as many configuration settings as possible in a configuration file. Configuration files support XCOPY deployment, and you can edit them easily using any text editor, including Notepad. They can store virtually any kind of information, from simple strings to complex objects. Unfortunately, .NET 1.1 configuration files have a couple of important shortcomings, but I'll show you how to work around these.
Let's begin with the basics. You must name a .NET configuration file after the EXE or DLL assembly it refers to, and you must give it a config extension, such as MyApp.exe.config or mylibrary.dll.config. For example, all ASP.NET configuration files are named web.config. A configuration file can include one or more sections that contain user-defined settings. Odds are that you're familiar with the <appSettings> section, which can contain one or more <add> elements with a key and a value attribute:
<configuration>
<appSettings>
<add key="name" value="Joe Doe" />
</appSettings>
</configuration>
You can create the skeleton of a config file from inside Visual Studio .NET by adding a new item of type Assembly Configuration File to the current project. VS.NET creates this file in the project directory with the name App.config, but copies it to the actual output directory when compiling the project.
VS.NET assumes that all values held in the appSettings section are strings, and you can read them using the ConfigurationSettings type (in the System.Configuration namespace):
Dim settings As NameValueCollection = _
ConfigurationSettings.AppSettings
Dim name As String = settings("name")
If you want to read a value that isn't a string, you must force a conversion to the target type, using one of the language functions such as CInt or CDbl, or one of the methods of the Convert type. If you need to assign the value to the property of a Windows Forms control, you can have VS.NET generate both the configuration file and the code that assigns the property by clicking on the button in the DynamicProperties element in the Properties window and assigning a key to the property (see Figure 1). Visual Studio .NET marks the property whose value you read from the config file with a small cyan icon to the right of its name in the Properties window.
Try Other Config Formats
In some cases, the format of the <appSettings> section isn't exactly what you need for your configuration data. For example, assume you want to parse this configuration file:
<configuration>
<cache duration="60" size="100" />
</configuration>
Back to top
|