[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Save and restore program settings in C#

save and restore program settings

To create settings at design time, open the Project menu and select Properties (at the bottom). On the Settings tab, enter a setting name, select its data type, and give it a value.

A setting's scope can be Application or User. Application settings are read-only. User settings can be modified by the program and are saved separately for each user.

The settings are saved in a XML file named Settings.settings. C# also creates a Settings.Designer.cs file that defines strongly-typed properties that you can use to get and set the setting values at run time.

Get or set a setting as in:

Properties.Settings.Default.Left = 100;

If you want to save changes to settings, call:


This example saves and restores its size, position, and TextBox contents when it starts and stops by using the following event handlers.

// Restore settings. private void Form1_Load(object sender, EventArgs e) { SetBounds( Properties.Settings.Default.Left, Properties.Settings.Default.Top, Properties.Settings.Default.Width, Properties.Settings.Default.Height); txtContent.Text = Properties.Settings.Default.Contents; } // Save the current settings. private void Form1_FormClosing(object sender, FormClosingEventArgs e) { Properties.Settings.Default.Left = Left; Properties.Settings.Default.Top = Top; Properties.Settings.Default.Width = Width; Properties.Settings.Default.Height = Height; Properties.Settings.Default.Contents = txtContent.Text; Properties.Settings.Default.Save(); }

For bonus points, you could modify the program to use a RichTextBox instead of a TextBox. You could add menus to let the user change text font, color, size, and so forth. Finally you could save and restore the control's Rtf property to preserve the text properties.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.