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!
Beware of calling
after each
Save() function actually saves your changes to the file but it is not reflected to your running code. Thus, your code keeps the copy of the previous version of the file.
When you call Save() at another location in your code, it writes over your first change, effectively reverting your first change back to original value. Very hard to pin down even when debugging.
I had the same problem.
To sort out the problem.
Go to the custom class in Visual Studio. Open the class and Check whether the constructor method.
If you have a constructor method, it should be parameterless. If you have a constructor with parameters, don;t worry. Create another constructor class without an parameters.
Repeat this for all sub classes within the class.
Rebuild and run. Now your settings should save.
Using Visual Studio 2013 - there is nothing I could do to make it work reliably, I would call Save and it did not save. Save and then immediately Reload and it still would not retain the values on subsequent runs (probably related to when I stopped debugging could not identify the root cause) - very frustrating, likely there is an underlying bug but I cannot prove it.
To avoid getting crazy with this I decided to use the registry - the most fundamental way to keep app settings for an app. Recommended for you all. Here is the code:
Usage:
Please have a look at this Question
Especially, try out the following code from an answer there:
Also, check out this overview, perhaps you ran into some limitation which is not easy to tell from your question.
This codeproject article might be of some help.