0

I am trying to add settings to Settings file dynamically. I use code below:

public PathSourceDir(int id)
{
    InitializeComponent();

    _id = id;

    SettingsProperty property = new SettingsProperty(Properties.Settings.Default.Properties["baseSetting"]);

    property.Name = "dynamicSettingName" + _id.ToString();
    property.DefaultValue = _id.ToString();
    Properties.Settings.Default.Properties.Add(property);
    Properties.Settings.Default.Save();

    //Read stored value
    var dynamicSetting = Properties.Settings.Default["dynamicSettingName" + _id.ToString()];
}

Code runs, however if I comment code lines where new property is created and Settings are saved, and run again, I get an exception:

System.Configuration.SettingsPropertyNotFoundException: 'The settings property 'dynamicSettingName6' was not found.

Meaning that setting previously was not saved in the file. However code was executed before also with id=6. Could you please advise what is wrong?

Creek Drop
  • 464
  • 3
  • 13
  • `Properties.Settings.Default.Properties["dynamicSettingName" + _id.ToString()]`? – mjwills Dec 07 '20 at 00:03
  • What is the _exact_ value of `property.Name` (don't guess, check in the `Immediate Window`)? – mjwills Dec 07 '20 at 00:04
  • Which version of .NET Core / Framework? – mjwills Dec 07 '20 at 00:05
  • @mjwills `Properties.Settings.Default.Properties["dynamicSettingName" + _id.ToString()]` returns null if saving is not performed. property.Name = "dynamicSettingName6". .Net Framework 4.7.2 – Creek Drop Dec 07 '20 at 00:09
  • @CreekDrop I'm not very familiar with WinForms but I would recommend referencing these links as I believe you're missing a few things. https://stackoverflow.com/questions/453161/how-can-i-save-application-settings-in-a-windows-forms-application https://learn.microsoft.com/en-us/dotnet/desktop/winforms/advanced/how-to-write-user-settings-at-run-time-with-csharp?view=netframeworkdesktop-4.8 – jdewerth Dec 07 '20 at 00:27

0 Answers0