Dienstag, 10. April 2012

Using .NET App.Config / Settings.settings

To use Settings.settings / app.config in your .NET (C#) windows forms app:

1. In the Solution Explorer right-click on your project, select "Add" > "New Item"
2. Select "Settings File", specify a meaningful name and click "Add". The File is created, added to your project and displayed.
3. Enter some setting 'fields' and their types you wish to maintain as application settings, much like a ressources file. A correspoinding app.config file will be generated / extended (this is where the actual values will be kept).

4. To access those app settings (e.g. when loading your application)

[NameOfTheSettingsFile] lastConfiguration = [NameOfTheSettingsFile].Default;
this.SomePropertyA = lastConfiguration.[SomeFieldYouHaveDefinedInTheSettingsFile];
this.SomePropertyB = lastConfiguration.[SomeOtherFieldYouHaveDefinedInTheSettingsFile]

5. To save/update app configuration (e.g. upon exiting or when options have been edited)

[NameOfTheSettingsFile] lastConfiguration = [NameOfTheSettingsFile].Default;
lastConfiguration.[SomeFieldYouHaveDefinedInTheSettingsFile] = this.SomePropertyA;
lastConfiguration.[SomeOtherFieldYouHaveDefinedInTheSettingsFile] = this.SomePropertyB;

lastConfiguration.Save();