Microsoft KB Archive/815785

= How to store custom information to and retrieve custom information from an application configuration file by using Visual C++ .NET or Visual C++ 2005 =

Article ID: 815785

Article Last Modified on 5/12/2007

-

APPLIES TO


 * Microsoft Visual C++ 2005 Express Edition
 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft Visual C++ .NET 2002 Standard Edition
 * Microsoft .NET Framework 1.1
 * Microsoft .NET Framework 1.0

-







For a Microsoft Visual Basic .NET version of this article, see 313405.



For a Microsoft Visual C# .NET version of this article, see 815786.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System::Configuration
 * System::Collections
 * System::Collections::Specialized

IN THIS TASK

 * SUMMARY
 * Requirements
 * Create a Console Application That Reads the Content of a Configuration File
 * Complete Code Listing
 * Complete Configuration File Listing (ConConfig.exe.config)
 * Verify That Your Application Works
 * Troubleshooting
 * REFERENCES



SUMMARY
This article describes how to store custom information in the configuration (.config) file of an application. This article also describes how an application can retrieve stored information from the associated configuration file during run time. The concepts that are described are helpful when you must define data that is associated with an application.

Back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Windows 2000, Microsoft Windows XP, or Microsoft Windows Server 2003
 * Microsoft Visual Studio .NET or Microsoft Visual Studio 2005

This article assumes that you are familiar with the following topics:
 * XML
 * The Microsoft .NET Framework configuration files

Back to the top

Create a Console Application That Reads the Content of a Configuration File
You can store application settings in the configuration file that is associated with an application. Configuration files exist in XML format.

The System::Configuration namespace and the System::Collections::Specialized namespace in the .NET Framework class library contain classes that you can use to retrieve information from the configuration file of a .NET application during run time. Additionally, the System::Collections namespace contains classes that you can use to iterate through a NameValueCollection object. You can read values to the NameValueCollection object from the configuration file.

To create a console application that reads the contents of an associated configuration file during run time, follow these steps:  Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005. On the File menu, point to New, and then click Project. In Visual Studio .NET 2002, click Visual C++ Projects under Project Types, and then click Managed C++ Application under Templates.

In Visual Studio .NET 2003, click Visual C++ Projects under Project Types, and then click Console Application (.NET) under Templates.

In Visual Studio 2005, click Visual C++ under Project Types, and then click CLR Console Application under Templates. In the Name text box, type ConConfig, and then click OK. On the View menu, click Solution Explorer. In Solution Explorer, right-click ConConfig, point to Add, and then click Add New Item. The Add New Item - ConConfig dialog box appears.</li> Click XML File (.xml) under Templates.

Note In Visual Studio 2005, expand Visual C++, click Web, and then click XML File (.xml) under Templates.</li> In the Name text box, type ConConfig.exe.config, and then click Open.

Note In Visual Studio 2005, click Add.</li>  You can use an application configuration file to store custom application settings that you can save in the key-value pair format. You can include   elements in the <appSettings> section of the associated configuration file of an application. Each key-value pair has one   element. An   element has the following format: <add key=&quot;Key0&quot; value=&quot;0&quot; /> Add an <appSettings> section with   elements to the configuration file of the application. Add this section between the   tag and the   tag.

For example, the following code represents a configuration file that includes an <appSettings> section that contains the following three key-value pairs: <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?> <appSettings> <add key=&quot;Key0&quot; value=&quot;0&quot; /> <add key=&quot;Key1&quot; value=&quot;1&quot; /> <add key=&quot;Key2&quot; value=&quot;2&quot; /> </appSettings> </li> In Solution Explorer, double-click ConConfig.cpp to display the code window.</li>  In the ConConfig.cpp file, add the following code before the _tmain function: using namespace System::Configuration; using namespace System::Collections; using namespace System::Collections::Specialized; Note If you are using Visual C++ .NET 2002, add the following additional code before the using directives:  To contain a value that you can retrieve from a configuration file key that exists in the <appSettings> section of the configuration file, declare a String data type variable in the _tmain function as follows: String * sAttr ; </li>  To retrieve a value for a specified key from the <appSettings> section of the configuration file, use the Get method of the AppSettings property of the ConfigurationSettings class. The ConfigurationSettings class is in the System.Configuration namespace. The get_AppSettings property getter function returns the AppSettings property. When the Get method of the AppSettings property receives an input String data type parameter that contains a key, the application retrieves the value that is associated with the key.
 * 1) using <System.Dll>
 * 2) include <tchar.h> </li>

The following code retrieves the value for the Key0 key from the associated configuration file. The code then assigns this value to the sAttrString data type variable. If a value does not exist for this key, the sAttr variable stores nothing. sAttr = ConfigurationSettings::get_AppSettings->Get(S&quot;Key0&quot;); </li>  To display the value that the application retrieves in the Console window, use the Console::WriteLine method as follows: Console::WriteLine(S&quot;The value of Key0: {0}&quot;, sAttr); </li>  You can use one reference to the AppSettings property to retrieve all the key-value pairs from the <appSettings> section of the configuration file. When you use the AppSettings property, the application retrieves all associated key-value pairs. These pairs are stored in a NameValueCollection object. The NameValueCollection object contains key-value entries for each key that the application retrieves. To retrieve all the key-value pairs from the configuration file, use the following code: NameValueCollection * sAll ; sAll = ConfigurationSettings::get_AppSettings; </li>  The AllKeys property of the NameValueCollection class references an array of String data types. This array contains an entry for each key that the application retrieves. Unlike Visual Basic .NET and Visual C# .NET, Visual C++ .NET does not support the foreach construct to iterate through a collection. Use an IEnumerator interface pointer to iterate through the array of String data types to access each key that the application retrieves. The GetEnumerator method returns an IEnumerator interface pointer that permits you to iterate through a collection. Each key entry in the array of String data types that is returned by the GetEnumerator method is an IEnumerator interface pointer.

Implement a while loop to iterate through the array of String data types by using the MoveNext method and the Current method of the IEnumerator interface. Use the dynamic_cast operator to convert the IEnumerator interface pointer to a String data type pointer. Use the Console::WriteLine method to display a key and the associated value in the Console window. The current key that the application processes is in the s variable. Use this variable as an index in the Item property of the sAll NameValueCollection object to obtain the associated value for a key. To do this, use the following code: IEnumerator* myEnum = sAll->AllKeys->GetEnumerator;

while (myEnum->MoveNext) {   String* s = dynamic_cast<String*>(myEnum->Current); Console::WriteLine(S&quot;Key: {0} Value: {1}&quot;, s ,sAll->Item[s]); } Console::ReadLine; </li> Press the CTRL+SHIFT+B key combination to build the application.</li> Start Windows Explorer, and then locate the folder that contains the application files.</li> Copy the ConConfig.exe.config file from this folder to the Debug folder that exists in the folder.</li></ol>

Back to the top

Complete Code Listing
// This is the main project file for Visual C++ .NET application project that is // generated by using an Application Wizard.


 * 1) include &quot;stdafx.h&quot;


 * 1) using <mscorlib.dll>

// In Microsoft Visual C++ .NET 2002, uncomment the following two lines of code: //#using <System.Dll> //#include <tchar.h>

using namespace System; using namespace System::Configuration; using namespace System::Collections; using namespace System::Collections::Specialized;

int _tmain {   try {       String  * sAttr ; // Read a particular key from the configuration file. sAttr = ConfigurationSettings::get_AppSettings->Get(S&quot;Key0&quot;); Console::WriteLine(S&quot;The value of Key0: {0}&quot;, sAttr); // Read all keys from the configuration file. NameValueCollection * sAll ; sAll = ConfigurationSettings::get_AppSettings;

IEnumerator* myEnum = sAll->AllKeys->GetEnumerator;

while (myEnum->MoveNext) {           String* s = dynamic_cast<String*>(myEnum->Current); Console::WriteLine(S&quot;Key: {0} Value: {1}&quot;, s ,sAll->Item[s]); }   }    catch(System::Configuration::ConfigurationException *ex) {       Console::WriteLine(ex->Message); }   catch(Exception *ex) {       Console::WriteLine(ex->Message); }

Console::ReadLine; return 0; } Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps:
 * 1) Click Project, and then click   Properties.

Note  is a placeholder for the name of the project.
 * 1) Expand Configuration Properties, and then click General.
 * 2) Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.

For more information about the common language runtime support compiler option, visit the following Microsoft Web site:

/clr (Common Language Runtime Compilation)

http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx

Back to the top

Complete Configuration File Listing (ConConfig.exe.config)
<?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?> <appSettings> <add key=&quot;Key0&quot; value=&quot;0&quot; /> <add key=&quot;Key1&quot; value=&quot;1&quot; /> <add key=&quot;Key2&quot; value=&quot;2&quot; /> </appSettings> Back to the top

Verify That Your Application Works
Press the CTRL+F5 key combination to start the application. A console window displays 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 Back to the top

Troubleshooting
<ul> The configuration file is in XML format. Make sure that you follow all XML syntax rules. Remember that XML is case-sensitive. If your XML code is not well-formed, or if an XML element is misspelled, you receive a System::Configuration::ConfigurationException exception.

For example, if you add the key attribute of an   element with an uppercase &quot;K&quot; instead of a lowercase &quot;k,&quot; or if the <appSettings> section appears as <AppSettings> (with an uppercase &quot;A&quot; instead of a lowercase &quot;a&quot;), you receive an error message.</li> Save the configuration file in the same folder as the associated application.</li> <li>You must use the following syntax for the configuration file name:

. .config

Where  is the name of the application,   is the file type of the application (for example, .exe), and .config is a required suffix.</li></ul>

Back to the top

<div class="references_section">