How to Create and Use Configuration Files


Here an article with a little more beginner tilt that shows how to create and use configuration files:

To store runtime settings, also known as initialization files, also known as application configuration files, and access them from Visual Studio .NET in C#, do the following:

  1. In Visual Studio .NET, chose File -> New -> File -> General -> Text file, and click "Open". A new window named 'TextFile1" (or TextFile2, etc.) will appear.

    Chose File -> Save TextFile2 As? and go to the Bin\Debug directory. Name the file with the same name as the .exe file of your project, adding a .config extension (example: yourApplication.exe and yourApplication.exe.config).

  2. Note: if you're compiling for release, copy it into the Bin\Release directory, or just create a shortcut in the release directory to the one in the debug directory.

  3. Chose File -> Add Existing Item and chose the config file you've just created.

  4. In the file you've now named yourApplication.exe.config, insert the following text:

  5. <?xml version="1.0" encoding="utf-8" ?>
    <
    configuration>
    <
    appSettings>
    <
    add key="Key1" value="Kevin" />
    <
    add key="Key2" value="150" />
    <
    add key="Key3" value="Rice" />
    </
    appSettings>
    </
    configuration>

  6. Save the configuration file again with control-s.

  7. In your application, add code like the following example:

    [STAThread]

    static void Main(string[] args)
    {
    string test1 = System.Configuration.ConfigurationSettings.AppSettings["Key1"];
    string test2 = System.Configuration.ConfigurationSettings.AppSettings["Key2"];
    string test3 = System.Configuration.ConfigurationSettings.AppSettings["Key3"];
    System.Console.WriteLine("test1="+test1+", test2="+test2+", test3="+test3+".");
    string throwaway = System.Console.ReadLine();
    return;
    }

  8. Run your application and see if this works. It should.

  9. Beware of having 2 keys with the same name. This is permissible, but then the value is a data structure containing both values.


Similar Articles