C# Setting load and save

2019-07-25 09:13发布

问题:

I trying to load and save setting with this code but when I closing and rerun program the settings not loaded. By default the settings was blank. I have no error.

private void Form1_Load(object sender, EventArgs e)
{
      txtUsername.Text = Properties.Settings.Default.Username;
      txtPassword.Text = Properties.Settings.Default.Password;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
      Properties.Settings.Default.Username = txtUsername.Text;
      Properties.Settings.Default.Password = txtPassword.Text;
}

回答1:

try

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
  Properties.Settings.Default.Username = txtUsername.Text;
  Properties.Settings.Default.Password = txtPassword.Text;
  Properties.Settings.Default.Save();
}


回答2:

How To: Write User Settings at Run Time with C# If you want to persist the changes to the settings between application sessions, call the Save method, as shown below:;

Properties.Settings.Default.Save();

You need to call Save() at the end of Form1_FormClosing