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:
- 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).
- 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.
- Chose File -> Add Existing Item and chose the config file you've just created.
- In the file you've now named yourApplication.exe.config, insert the following text:
- <?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>
- Save the configuration file again with control-s.
- 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;
}
- Run your application and see if this works. It should.
- Beware of having 2 keys with the same name. This is permissible, but then the value is a data structure containing both values.