C# Settings.Default.Save() not saving? [duplicate]

2020-02-09 01:06发布

this bug is pretty unusual. Basically my code will change the Settings.Default.Example then save and restart the program. Then when it loads, it shows a message box. However oddly, it shows a empty value when the form loads.

Here is my code:

Main.cs
    private void Button1_Click(object sender, EventArgs e)
    {
        Settings.Default.Example = "Somevalue"; //Sets a value to the settings
        Settings.Default.Save(); // Save it
        MessageBox.Show(Settings.Default.Example); //Confirming it has been saved
        Application.Restart();
    }

    private void Main_Load(object sender, EventArgs e)
    {
        MessageBox.Show(Settings.Default.Example); // Here is the weird part, it shows empty.
    }

The MessageBox will show "Somevalue" when the button was clicked then the applcation restarts and the MessageBox that showed was empty. However repeating the process by clicking the button once more and restarting it does show the "Somevalue" MessageBox. Please help! Many Thanks!

标签: c# settings
10条回答
我只想做你的唯一
2楼-- · 2020-02-09 01:32

If your AssemblyInfo.cs file has a * in Assembly Version then it's refreshing the file every build so you won't see persistence or reliability until you change that to a hard number and rebuild all, then retest everything.

查看更多
劳资没心,怎么记你
3楼-- · 2020-02-09 01:34

did you try calling ConfigurationManager.RefreshSection before checking that it got saved ad you could try it again after the reload

查看更多
我命由我不由天
4楼-- · 2020-02-09 01:37

After a full day of researching and studying the subject, I was able to solve this by putting the Configuration to the user:

Using System.Configuration; 

Properties.Settings.Default.strinconn = txt_stringconn.Text;
Properties.Settings.Default.Save ();
Properties.Settings.Default.Upgrade ();
MessageBox.Show ("Saved Settings");
Application.Restart ();
查看更多
冷血范
5楼-- · 2020-02-09 01:38

Maybe you ran the same mistake as I did: setting the setting's scope to Application. Those kind of settings are not saved.

Set it to User to solve the problem.

查看更多
一夜七次
6楼-- · 2020-02-09 01:40

rene is correct - you need to call Default.Reload after calling the Save method:

Settings.Default.Save();
Settings.Default.Reload();

Possibly a bug - ?

Posting as a reply to increase visibility -

查看更多
你好瞎i
7楼-- · 2020-02-09 01:42

If you need to test your application how actually working in this case better to run the exe file. When you run on visual studio on debug mode when those settings saving it will take some time. Go to debug folder and run the exe you will get the messages as expected.

查看更多
登录 后发表回答