Click here to Skip to main content
Click here to Skip to main content

Application settings in VB.NET 2.0 and Visual Studio 2005

By , 11 Jan 2006
 
Prize winner in Competition "VB.NET Oct 2005"

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.

Sample Image - AppSettings2005.jpg

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.

Sample Image - AppSettings2005_save.jpg

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
        'Set textboxes and form name from application and user settings

        'Notice how the application setting property is ReadOnly
        Me.Text = My.Settings.MainFormText

        'Notice how the user settings are writable
        Me.Size = My.Settings.MainFormSize
        Me.Location = My.Settings.MainFormLocation

        Me.txtFormText.Text = My.Settings.MainFormText

        'Show the form now
        Me.Visible = True
    End Sub

In the form's FormClosing event, we save the form's size and location values to the current values.

Main form closing

Private Sub Form1_FormClosing _
    (ByVal sender As Object, _
    ByVal e As System.Windows.Forms.FormClosingEventArgs) _
    Handles Me.FormClosing
        Try
            'Set my user settings MainFormSize to the
            'current(Form) 's size
            My.Settings.MainFormSize = Me.Size

            'Set my user setting MainFormLocation to
            'the current form's location
            My.Settings.MainFormLocation = Me.Location

            'Save the user settings so next time the
            'window will be the same size and 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

itoleck
Help desk / Support www.swarmsoft.net
United States United States
Member
Chad Schultz
13 years of Computer Information Systems experience
MCSE, MCAD, MCTS SharePoint
 
Blog: ChadSchultz.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionProblem with the Me.FormClosingmembertomk650528 Jun '12 - 15:38 
When I entered:
Private Sub Form1_Close(ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
when I try to run the program, it gives me this error:
 
Method 'Private Sub Form1_Close(ByVal e As System.Windows.Forms.FormClosingEventArgs)' cannot handle event 'Public Event FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs)' because they do not have a compatible signature... D:
QuestionHello how to make my.settings portable?memberleesong28 Feb '11 - 22:31 
hi, its a nice guide i rated it 5   Big Grin | :-D    Big Grin | :-D
How do i make it portable?
I'll copy from the directory you gave to local directory before application shutdown,
and copy from local directory to the directory you gave on form_load before loading settings from .config file
is this method the best?
 
Making Youtube Video Downloader Using VB.NET!
GeneralTweaking the code to handle window sizing bettermemberMartin Omander30 Sep '08 - 9:03 
The article was written to demonstrate how to read and write user settings and I think it did a great job. Thanks Chad!
 
As I used the code to handle window sizing in an app, I discovered two cases that aren't handled in the code above. To handle these cases I added a little code, which I thought I'd share.
 
Case 1: The user maximizes the window. Next time she opens the app, she expects the window to be maximized, but the code above doesn't do that.
 
Case 2: The user lowers screen resolution or stops using a second monitor. This happens all the time when I undock my laptop. The code above may place the window where it can't be seen.
 
To solve for these two use cases I add a setting of type bool called MainFormMaximized and use this code:
 
private void MainForm_Load(object sender, EventArgs e) {
  if (Properties.Settings.Default.MainFormMaximized) {
    this.WindowState = FormWindowState.Maximized;
  }
  else {
    Rectangle ProposedWindowRect = new Rectangle(Properties.Settings.Default.MainFormPosition, Properties.Settings.Default.MainFormSize);
    bool WindowWillFit = false;
    foreach (Screen S in Screen.AllScreens) {
      if (S.WorkingArea.Contains(ProposedWindowRect)) {
        WindowWillFit = true;
      }
    }
    if (WindowWillFit) {
      this.Location = Properties.Settings.Default.MainFormPosition;
      this.Size = Properties.Settings.Default.MainFormSize;
    }
    else {
      this.Location = new Point(0, 0);
      this.Size = new Size(600, 400);
    }
  }
}
 
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
  Properties.Settings.Default.MainFormPosition = this.Location;
  Properties.Settings.Default.MainFormSize = this.Size;
  Properties.Settings.Default.MainFormMaximized = (this.WindowState == FormWindowState.Maximized);
  Properties.Settings.Default.Save();
}
 
Enjoy!
 
/Martin
QuestionHow do I change ConnectionString in app.configmemberLeif Thomsen23 Aug '08 - 1:57 
I use a dialogbox on my startup form to find my Access database. I then want this to my connectionstring in app.config, but I get the failure connectionString is Readonly.
How do I get it writeable?
 
Leif
QuestionIs it safe?memberDan'M26 Oct '07 - 23:32 
Good article. I want to ask you that is it safe to save passwords like informations using this way ?
 
Thanks,
Dan
AnswerRe: Is it safe?memberdepmoddima2 Nov '07 - 0:00 
No, Isn't safe!! MS wrote:"...Application settings has no built-in facility for encrypting information automatically. You should never store security-related information, such as database passwords, in clear text. If you want to store such sensitive information, you as the application developer are responsible for making sure it is secure. If you want to store connection strings, we recommend that you use Windows Integrated Security and not resort to hard-coding passwords into the URL."
See "Limitations of Application Settings" on MSDN - http://msdn2.microsoft.com/en-us/library/k4s6c3a0.aspx
 
Have a nice day!
Dmitriy

QuestionExpress EditionmemberFREEYO17 Jul '07 - 15:19 
Can this be done in Visual Studio 2005 Express Edition?
 
FREEYO

Generalapplication settings in ToolStripMenuItemmemberjhon edison20 Apr '07 - 18:25 
Hello is possible add ToolStripMenuItem and saved to have with application settings???. I'm the created but not saved, when begin not change the aplication.. Saludos.
GeneralRe: application settings in ToolStripMenuItemmemberctwalker16 Aug '07 - 4:30 
jhon edison wrote:
Hello is possible add ToolStripMenuItem and saved to have with application settings???.

 
There is a problem with PropertyBinding and ToolStripMenuItems. The code to load the Settings is correctly built by VisualStudio, but the code to save the settings isn't built, you'll have to do this by hand.
 
Look in the Designer code for your module. In the Dispose sub add code to save your settings. Ex, if you want to save the state of a checked button.
 
My.Settings.ctlEventLogViewer_btnErrors_Checked = btnErrors.Checked
 
That's all it takes.
QuestionMy.Settings.Save for complex types?memberjerome51369 Apr '07 - 17:23 
I have an application with several simple types: boolean, int, strings...and it seems to save these fine. But anything that has a serializeAs="XML" like a webproxy, or hashtable or whatever doesn't save. Anyone else having this problem?
 
JL

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 11 Jan 2006
Article Copyright 2005 by itoleck
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid