0

I'm trying save settings for my application with tabs. Each tab show some data from path. I store it like this:

 private Dictionary<int, string> _listTabs = new Dictionary<int, string>();

when I create new tab, I add new Item in dictionary

 _listTabs.Add(listTabs.Count++,CurrentPath);

before closing programm I want to save this dictionary in settings:

foreach(KeyValuePair kvp in _listTabs)
{
  var property = new SettingsProperty(kvp.Key);
  property.DefaultValue = kvp.Value;
  Settings.Default.Properties.Add(property);
}
Settings.Defaut.Save();

But, it doesnt work. Where are the mistakes?

Mikhail Sokolov
  • 546
  • 1
  • 7
  • 18

3 Answers3

1

You'd need to tell us what the error is that you are seeing if the application is failing for some reason.

Also in your code above, I can't see any method to Save the settings

If you want to persist changes to user settings between application sessions, call the Save method, as shown in the following code:

Properties.Settings.Default.Save();

For more info on user settings take a look at Using Settings in C# with specific focus on the area of Using Settings at Run Time.

Once you've established that this works, check the user settings file. This Answer shows you where the settings are saved to.

Community
  • 1
  • 1
Mr Moose
  • 5,946
  • 7
  • 34
  • 69
0

When we create new settings at runtime, add to Properties collection and try to save it, the new settings do not actually get saved in the user.config file.

I faced the same issue and fixed it as follow:

  1. Create a dummy property in settings at design time: This will ensure that the user.config file will be created and settings would be saved in it. Now when we call Properties.Settings.Default.Save(); the default provider "LocalFileSettingsProvider" will save all the Properties in Settings.Default.Properties collections including the one added on runtime.

You will see that the new properties added to the collection at runtime are getting saved in the user.config file. But there is a second issue here which is when try to load the values from the user.config.

It will only load the value of the settings which are present at design time irrespective of other properties present in the user.config.

The fix I did for same is to add the property with some default value in the Properties collection again and then call following:

2 Load the property values from user.config:

SettingsProvider provider = Properties.Settings.Default.Providers["LocalFileSettingsProvider"];

SettingsPropertyValueCollection propertyValueCollection = provider.GetPropertyValues( Properties.Settings.Default.Context, Properties.Settings.Default.Properties);

This will load the value from the user.config into the PropertyValues collection and then those values can be used.

Hope it helps...

0

I noticed that the last line of your code reads

Settings.Defaut.Save();

I believe that there is a misspelling. Defaut should be Default.