Introduction
A new feature of .NET 2.0 and Visual Studio 2005 is the ability to save a user's application settings in a user.config file that is saved in the user's desktop profile.
Background
Until .NET 2.0, it was difficult to save a user's settings for an application. User settings had to be saved in the registry, in an .ini file, or in a custom text file. Now, it is possible to save settings for a user's application that will even move with them in a roaming desktop profile.
To view the non-roaming settings, open the user.config file located at %USERPROFILE%\Local Settings\Application Data\<Company Name>\<appdomainname>_<eid>_<hash>\<verison>\user.config.
To view the roaming user settings, open the user.config file located at %USERPROFILE%\Application Data\<Company Name>\<appdomainname>_<eid>_<hash>\<verison>\user.config.
Using the code
To add application or user settings to a project, right-click on the project name in the Solution Explorer window, and click Properties. Then, click on Settings in the left tab list.
When a setting is added to the Visual Studio designer, a public property is created in the My.Settings
namespace. Depending on the scope of the setting, the property will be ReadOnly
or writable. This allows you to programmatically change the user setting values and save them with the My.Settings.Save()
method.
A second way to save settings is to enable the 'Save My.Settings on Shutdown' setting in the application. To do this, right-click on the project name in the Solution Explorer window, and click Properties. Then, click on Application in the left tab list.
To restore the last saved dimensions of a form, we set the size and location of the form from the user settings in the form's Load
event.
Private Sub Form1_Load _
(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
Me.Text = My.Settings.MainFormText
Me.Size = My.Settings.MainFormSize
Me.Location = My.Settings.MainFormLocation
Me.txtFormText.Text = My.Settings.MainFormText
Me.Visible = True
End Sub
In the form's FormClosing
event, we save the form's size and location values to the current values.
Private Sub Form1_FormClosing _
(ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles Me.FormClosing
Try
My.Settings.MainFormSize = Me.Size
My.Settings.MainFormLocation = Me.Location
My.Settings.Save()
MsgBox("Your settings were saved successfully.", _
MsgBoxStyle.OkOnly, "Save...")
Catch ex As Exception
MsgBox("There was a problem saving your settings.", _
MsgBoxStyle.Critical, "Save Error...")
End Try
End Sub
Conclusion
You can use application and user settings for many things in .NET 2.0. Just remember that if you want to change the settings then the scope has to be set as User.
History
- Second revision - Moved around text and image to make the article more readable. Added a Conclusion section.
- Third revision - Updated user.config file paths, and added profile and auto save on exit explanation.