Use Visual C# to store and retrieve custom information from an application configuration file
This article introduces how to store custom information from a configuration file that you can retrieve later during run time by its associated application. It's helpful when you must define data that's associated with an application.
Note
The code in this article is targeting .NET Framework 2.0 and later versions. To know which specific versions the ConfigurationManager
class applies to, see the Applies to section.
Original product version: Visual C#
Original KB number: 815786
Requirements
The following list outlines the recommended hardware and software that you need:
- Microsoft Windows
- Visual C#
This article assumes that you're familiar with the following topics:
- Extensible Markup Language (XML)
- .NET configuration files
Create a console application that reads a configuration file
You can store application settings in the configuration file that is associated with the application. Configuration files are saved in XML format.
The System.Configuration
and the System.Collections.Specialized
namespaces in the .NET Framework include the necessary classes to retrieve information from a .NET application configuration file during run time.
To create a console application that reads the contents of an associated configuration file during run time, follow these steps:
Start Visual Studio .NET or Visual Studio.
On the File menu, point to New, and then select Project.
select Visual C# under Project Types, and then select Console Application under Templates. Name the project ConConfig. By default, Visual C# creates a class that is named Program.
Note
In Visual Studio .NET, select Visual C# Projects under Project Types, and then select Console Application under Templates. Name the project ConConfig. By default, Visual C# creates a class that is named Class1.
Make sure that the Solution Explorer window is visible. If it isn't visible, press the CTRL+ALT+L key combination.
In Solution Explorer, right-click the project name, select Add, and then select New Item.
In the Add New Item list, select XML File.
In the Name text box, type App.config, and then select Add.
You can use an application configuration file to collect custom application settings that you save in key/value format. You can include
<add>
elements in the<appSettings>
section of an associated configuration file. Each key/value pair has one<add>
element. An<add>
element has the following format:<add key="Key0" value="0" />
Add an
<appSettings>
section with<add>
elements to the configuration file between the<configuration>
and</configuration>
tags.For example, the following configuration file includes an
<appSettings>
section that specifies three key/value pairs:<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="Key0" value="0" /> <add key="Key1" value="1" /> <add key="Key2" value="2" /> </appSettings> </configuration>
In Solution Explorer, double-click Program.cs to display the code window. Add the following statements to your code module.
Note
These statements must appear before any other statements in the file.
using System.Configuration; using System.Collections.Specialized;
Add a reference to System.Configuration.dll by following these steps:
- On the Project menu, select Add Reference.
- In the Add Reference dialog box, select the .NET tab.
- Find and select the Component Name of
System.Configuration
. - select OK.
To hold the value from a configuration file key in the
<appSettings>
section of the configuration file, declare a string variable in theMain
section as follows:string sAttr;
To retrieve a value for a specified key from the
<appSettings>
section of the configuration file, use theGet
method of theAppSettings
property of the ConfigurationManager class. TheConfigurationManager
class is in theSystem.Configuration
namespace. When theAppSettings.Get
method receives a string input parameter that contains a key, the application retrieves the value that is associated with the key.The following code retrieves the value for the
Key0
attribute from the associated configuration file. The code then places this value in thesAttr
string variable. If a key doesn't exist for this value, nothing is stored insAttr
.sAttr = ConfigurationManager.AppSettings.Get("Key0");
To display the value that the application retrieves in the Console window, use
Console.WriteLine
as follows:Console.WriteLine("The value of Key0 is "+sAttr);
You can use one reference to the
AppSettings
property to retrieve all the key/value pairs in the<appSettings>
section. When you use theAppSettings
property, the application returns all associated key/value pairs. These pairs are stored in aNameValueCollection
type. TheNameValueCollection
contains key/value entries for each key that the application retrieves. TheNameValueCollection
class is in theSystem.Collections.Specialized
namespace.NameValueCollection sAll ; sAll = ConfigurationManager.AppSettings;
The
AllKeys
property ofNameValueCollection
references a string array that has an entry for each key that the application retrieves. Use a foreach construction to iterate through theAllKeys
array to access each key that the application retrieves. Each key entry inAllKeys
is a string data type.Inside the
foreach
construction, useConsole.WriteLine
to display the key and its associated value in the Console window. The current key that the application processes is ins
. Use it as an index in thesAllNameValueCollection
to obtain its associated value.foreach (string s in sAll.AllKeys) Console.WriteLine("Key: "+ s + " Value: " + sAll.Get(s)); Console.ReadLine();
Complete code listing
using System;
using System.Configuration;
using System.Collections.Specialized;
namespace ConConfig
{
class Program
{
static void Main(string[] args)
{
string sAttr;
// Read a particular key from the config file
sAttr = ConfigurationManager.AppSettings.Get("Key0");
Console.WriteLine("The value of Key0: " + sAttr);
// Read all the keys from the config file
NameValueCollection sAll;
sAll = ConfigurationManager.AppSettings;
foreach (string s in sAll.AllKeys)
Console.WriteLine("Key: " + s + " Value: " + sAll.Get(s));
Console.ReadLine();
}
}
}
Complete configuration file listing (ConConfig.exe.config)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Key0" value="0" />
<add key="Key1" value="1" />
<add key="Key2" value="2" />
</appSettings>
</configuration>
Verify that it works
Press F5 to run the code. The Console window should display the key/value pairs from the <appSettings>
section of the associated configuration file as follows:
The value of Key0: 0
Key: Key0 Value:0
Key: Key1 Value:1
Key: Key2 Value:2
Troubleshoot
The configuration file is saved in XML format. Make sure that you follow all XML syntax rules. Remember that XML is case-sensitive. If the XML isn't well formed, or if an element is misspelled, you receive a
System.Configuration.Configuration
exception.For example, if you add the key attribute of an
<add>
element with an uppercase K instead of a lowercase k, or if the<appSettings>
section appears as<AppSettings>
(with an uppercase A instead of a lowercase a), you receive an error message.The configuration file must be saved in the same folder as its associated application.
You must use the following syntax for the configuration file name:
<ApplicationName>.<ApplicationType>.configWhere <ApplicationName> is the name of the application. <ApplicationType> is the type of application, such as
.exe
. And.config
is the required suffix.