Save and restore program settings in C#

save and restore program settings

This example shows one way you can save and restore program settings when a program stops and starts.

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:

Properties.Settings.Default.Save();

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 Example




This entry was posted in programs. Bookmark the permalink.

One Response to Save and restore program settings in C#

  1. Pingback: Easily save and restore a form's settings in the Registry in C# |

Leave a Reply

Your email address will not be published. Required fields are marked *