Settings.settings
This stores preferences on the disk. This file can be used for writing a setting to disk when a program exits, and then reading it back when the program is started again.
There are some mechanisms for programmers to easily store settings on the disk, and access them in memory whenever needed. Settings.settings
makes programs faster to develop.
This example code is run when we start up the program. We retrieve the string
and display it in a text box in Windows Forms.
FormClosing
is called.string
to the last input string
when the FormClosing
event handler is invoked.// // Read in a value from the Setting.settings file. // SavedInputString is just a custom variable which can be named anything. // Set the Text of an input box to the property. // inputBox.Text = Properties.Settings.Default.SavedInputString;void TextWindow_FormClosing(object sender, FormClosingEventArgs e) { // // We are going to write to the settings in our code. // We take the results of a function, and set the settings string equal to it. // Properties.Settings.Default.SavedInputString = SanitizeInput(inputBox.Text); // // Now, we need to save the settings file. // If we don't save it, they disappear. // By saving it, we will be able to use all the settings exactly // as they are now, the next time the program is run. // Properties.Settings.Default.Save(); }
FormClosing
eventThere is one method call that needs to be made when the program exits. That is easy to do, however, and making a simple FormClosing
event handler is sufficient.
// // Retrieve a value from the Settings.settings file. // The string was manually added to the settings file in the table in Visual Studio. // long expireTime = Properties.Settings.Default.ExpireMs;
In a typical Windows Forms project, there is a folder called Properties and a file called Settings.settings
in that folder.
Double
click on the Settings.settings
file and you should see a settings table.int
, string
). Set the value in the right side.This setting indicates whether the setting will be changed by the user or not. Also, the user setting is reset by each user installation.
There is a Scope column in the table. There are two options in each cell there: Application and User. Next, we describe the scope values available and their meanings.
We used the Settings.settings
file in Visual Studio with the C# language. The resources are automatically turned into regular properties.