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



The information in this article applies to:

  • Microsoft Visual C++ 2005 Express Edition
  • Microsoft Visual C++ .NET (2003)
  • Microsoft Visual C++ .NET (2002)
  • 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

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:
  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. 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.
  4. In the Name text box, type ConConfig, and then click OK.
  5. On the View menu, click Solution Explorer.
  6. In Solution Explorer, right-click ConConfig, point to Add, and then click Add New Item. The Add New Item - ConConfig dialog box appears.
  7. Click XML File (.xml) under Templates.

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

    Note In Visual Studio 2005, click Add.
  9. 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 <add> elements in the <appSettings> section of the associated configuration file of an application. 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 of the application. Add this section between the <configuration> tag and the </configuration> 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="1.0" encoding="utf-8" ?>
    <configuration>
       <appSettings>
          <add key="Key0" value="0" />
          <add key="Key1" value="1" />
          <add key="Key2" value="2" />
       </appSettings>
    </configuration>
    
  10. In Solution Explorer, double-click ConConfig.cpp to display the code window.
  11. 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:
    #using <System.Dll>
    #include <tchar.h>
  12. 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 ;
  13. 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.

    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"Key0");
  14. To display the value that the application retrieves in the Console window, use the Console::WriteLine method as follows:
    Console::WriteLine(S"The value of Key0: {0}", sAttr);
  15. 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();
  16. 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"Key: {0} Value: {1}", s ,sAll->Item[s]);
    }
    Console::ReadLine();
  17. Press the CTRL+SHIFT+B key combination to build the application.
  18. Start Windows Explorer, and then locate the folder that contains the application files.
  19. Copy the ConConfig.exe.config file from this folder to the Debug folder that exists in the folder.
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.

#include "stdafx.h"

#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"Key0");
        Console::WriteLine(S"The value of Key0: {0}", 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"Key: {0} Value: {1}", 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 <ProjectName> Properties.

    Note <ProjectName> is a placeholder for the name of the project.
  2. Expand Configuration Properties, and then click General.
  3. 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="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
      <add key="Key0" value="0" />
      <add key="Key1" value="1" />
      <add key="Key2" value="2" />
   </appSettings>
</configuration>
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

  • 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 <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.
  • Save the configuration file in the same folder as the associated application.
  • You must use the following syntax for the configuration file name:

    ApplicationName.ApplicationType.config

    Where ApplicationName is the name of the application, ApplicationType is the file type of the application (for example, .exe), and .config is a required suffix.
Back to the top

REFERENCES

For more information about the ConfigurationSettings.AppSettings property, visit the following Microsoft Developer Network (MSDN) Web site:For more information about the System.Configuration namespace, visit the following MSDN Web site:Back to the top

Modification Type:MajorLast Reviewed:1/6/2006
Keywords:kbProgramming kbCollectionClass kbConfig kbConsole kbCollections kbHOWTOmaster KB815785 kbAudDeveloper