Simplest way to have a configuration file in a Windows Forms C# application
You want to use an App.Config.
When you add a new item to a project there is something called Applications Configuration file. Add that.
Then you add keys in the configuration/appsettings section
Like:
<configuration>
<appSettings>
<add key="MyKey" value="false"/>
Access the members by doing
System.Configuration.ConfigurationSettings.AppSettings["MyKey"];
This works in .NET 2 and above.
Clarification of previous answers...
Add a new file to your project (Add → New Item → Application Configuration File)
The new configuration file will appear in Solution Explorer as App.Config.
Add your settings into this file using the following as a template
<configuration> <appSettings> <add key="setting1" value="key"/> </appSettings> <connectionStrings> <add name="prod" connectionString="YourConnectionString"/> </connectionStrings> </configuration>
Retrieve them like this:
private void Form1_Load(object sender, EventArgs e) { string setting = ConfigurationManager.AppSettings["setting1"]; string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString; }
When built, your output folder will contain a file called <assemblyname>.exe.config. This will be a copy of the App.Config file. No further work should need to be done by the developer to create this file.
From a quick read of the previous answers, they look correct, but it doesn't look like anyone mentioned the new configuration facilities in Visual Studio 2008. It still uses app.config (copied at compile time to YourAppName.exe.config), but there is a UI widget to set properties and specify their types. Double-click Settings.settings in your project's "Properties" folder.
The best part is that accessing this property from code is typesafe - the compiler will catch obvious mistakes like mistyping the property name. For example, a property called MyConnectionString in app.config would be accessed like:
string s = Properties.Settings.Default.MyConnectionString;