Home > OS >  How to save Settings at runtime in C# Winforms App
How to save Settings at runtime in C# Winforms App

Time:07-16

I am developing a fairly basic winforms app in .Net 6 that has some settings that I need to save locally at runtime.

THis piece of Code

Properties.Settings.Default["comPort"] = cboComPorts.Text;

I get the error:

System.Configuration.SettingsPropertyNotFoundException HResult=0x80131500 Message=The settings property 'comPort' was not found. Source=System.Configuration.ConfigurationManager

Ideally - I would like to save the settings in a file at runtime

  • creating a new setting if it doesn't exist
  • or overwrite the setting if it does exist.

I have tried creating a "Settings.settings" file as well - but I can't quite get my head around why it won't write the setting.

CodePudding user response:

I don't think you're properly adding the settings file. Add a folder to your project named Properties. For Visual Studio right click on the folder and select Add -> New Item -> Settings File. You should have Settings.Designer.cs and Settings.settings in your properties file. It should look like this when you open it;

enter image description here

Fetch, set and update the setting like so;

int savedPort = Properties.Settings.Default.comPort;
Properties.Settings.Default.comPort = 1;
Properties.Settings.Default.Save();

CodePudding user response:

How To: Write and Persist User Settings at Run Time with C# Access the setting and assign it a new value as shown in this example: C# Copy. ... If you want to persist the changes to the settings between application sessions, call the Save method as shown in this example: C# Copy.

  • Related