How to Save Application Settings in a Windows Forms Application

How can I save application settings in a Windows Forms application?

If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.

Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings and Settings.Designer.settings that contain the singleton class Settings inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:

Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file

This technique is applicable both for console, Windows Forms, and other project types.

Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only.

Reference: How To: Write User Settings at Run Time with C# - Microsoft Docs

Save Settings in a .NET Winforms Application

At some point, the answer boils down to a matter of taste. I'd say you'll end up with at least these options:

  • store it in the registry, where you have the HKEY_CURRENT_USER key. Everything under it is user-specific. This is usually preferred when you want to store a bunch of small key-value pairs. The main advantage of this system is that your settings are easy to find and share throughout several different applications. To follow this path, you can start from here.
  • using .NET Application settings, provides the easiest way to access your settings at runtime. Again, it's better for using with key-value pairs of small-sized data. IMO, the main advantages of this method is its simplicity and the fact that it empowers you to use some .NET classes as values (not forcing you to convert everything into more basic types). To follow this path, you can start from here.
  • store it in User Data folders, which are usually hidden under the user's profile directory. This is preferred when you want to store a large amount of data or any number of files. The main advantage of this method is that you can manipulate your data as you would with any files (that may also be a disadvantage). To follow this path, you can start from here.

How to save Application Settings to a different location and file name

Update. I have installed a new Settings Provider and it is working well. It saves the XML to the app folder. I have also set up INI files to save the settings. Using both a custom path and custom file name. It allows for multiple INI files to be created. This also works extremely well.

Edit: Updated code (and instructions) so it is no longer necessary to create any custom folder manually. If it does not exist, it will be created.

The XML Settings Provider developers project is located here:

Settings Providers on Github

The INI file developers project (and demo) is located here:

C# WinForms Ini File demo on Github

Below are the instructions for setting up the new Settings Provider with an XML file and following that are the instructions for saving the settings to INI files (both types can be used in the same project at the same time, as I am doing here):

Using a new Settings Provider to save settings in an XML file:

1.
Setup the Application Settings (in Solution Explorer, right-click on the App. Then Select: Properties. Then open: Settings).

Name: txtFullName
Type: String
Scope: User
Value: John Doe

Name: txtSchool
Type: String
Scope: User
Value: Oxford

Name: txtClass
Type: String
Scope: User
Value: 4B

Name: chkActiveStudent
Type: bool
Scope: User
Value: True

2.
Install, from NuGet the new Settings Provider (in Solution Explorer, right-click on: References. Then Select: Manage NuGet Packages. Then search for: PortableSettingsProvider. Install it).

3.
In Program.cs modify static void Main(). Add to it the lines below.

//PortableSettingsProvider.SettingsFileName = "portable.config";
//PortableSettingsProvider.SettingsDirectory = "c:\\\testconfig\\\school";
//System.IO.Directory.CreateDirectory(PortableSettingsProvider.SettingsDirectory);
PortableSettingsProvider.ApplyProvider(Properties.Settings.Default);

If accepting the default settings (the config file, portable.config, will be created in the applications folder), a properly edited static void Main() entry would look like the below.

static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//PortableSettingsProvider.SettingsFileName = "portable.config";
//PortableSettingsProvider.SettingsDirectory = "c:\\testconfig\\school";
//System.IO.Directory.CreateDirectory(PortableSettingsProvider.SettingsDirectory);
PortableSettingsProvider.ApplyProvider(Properties.Settings.Default);
Application.Run(new MyTestApp());
}

3a.
To choose a different filename and location, remove the comments (//) and change to your preference for filename and location (double slashes are needed between the folder names). In this example I use settings.config as the filename and c:\testconfig\school as the path). In this case a properly edited static void Main() entry would look like the below.

static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
PortableSettingsProvider.SettingsFileName = "settings.config";
PortableSettingsProvider.SettingsDirectory = "c:\\testconfig\\school";
System.IO.Directory.CreateDirectory(PortableSettingsProvider.SettingsDirectory);
PortableSettingsProvider.ApplyProvider(Properties.Settings.Default);
Application.Run(new MyTestApp());
}

3b.
If you would like the settings directory to be created in a subfolder of the applications working directory, then change the code to include the subfolder name (in this example I use settings.config as the filename and Settings as the subfolder). In this case a properly edited static void Main() entry would look like the below.

static void Main()
{
Application.EnableVisualStyles();
PortableSettingsProvider.SettingsFileName = "settings.config";
var strSettingsDirectory = Directory.GetCurrentDirectory() + "\\Settings";
System.IO.Directory.CreateDirectory(strSettingsDirectory);
PortableSettingsProvider.SettingsDirectory = strSettingsDirectory;
PortableSettingsProvider.ApplyProvider(Properties.Settings.Default);
Application.Run(new MyTestApp());
}

4.
Still in Program.cs, add the following line to the bottom of the existing using section.

using Bluegrams.Application;

5.
On the form create some controls (these will correspond to the Application Settings made in step 1).

TextBox. Name: txtFullName

TextBox. Name: txtSchool

Textbox. Name: txtClass

Checkbox. Name: chkActiveStudent

Button. Name: btnLoadSettings Text: Load Config

Button. Name: btnSaveSettings Text: Save Config

6.
Enter the code for the Load Config buttons click events (btnLoadSettings).

private void btnLoadSettings_Click(object sender, EventArgs e)
{
txtName.Text = Properties.Settings.Default.txtName.ToString();
txtSchool.Text = Properties.Settings.Default.txtSchool.ToString();
txtClass.Text = Properties.Settings.Default.txtClass.ToString();

if (Properties.Settings.Default.chkActiveStudent == true)
{
chkActiveStudent.Checked = true;
}
else
{
chkActiveStudent.Checked = false;
}
}

7.
Enter the code for the Save Config buttons click events (btnSaveSettings).

private void btnSaveSettings_Click(object sender, EventArgs e)
{
Properties.Settings.Default.txtName = txtName.Text;
Properties.Settings.Default.txtSchool = txtSchool.Text;
Properties.Settings.Default.txtClass = txtClass.Text;

if (chkActiveStudent.Checked == true)
{
Properties.Settings.Default.chkActiveStudent = true;
}

else
{
Properties.Settings.Default.chkActiveStudent = false;
}

Properties.Settings.Default.Save();
}

8.
That’s it.

Run the app.
Load the settings using the first button).
Make some changes to the text on the controls.
Save them using the second button.

If you have not created a custom filename and/or path then in your app folder there should be a new file: portable.config.

Mine is located at: C:\Users\flakie\source\repos\TestApp\TestApp\bin\Debug

You can open the file in an txt/xml editor to verify the values were set.

If you run the app again, and load settings, you should see the new values.

The Code for Saving Settings to Multiple INI Files

The following instructions are easier to implement.
They do not require you to set-up the Application Settings as they are not used.
The settings will be saved in 1 or more INI files.

The path can be changed on-the-fly (though a default is set), as can the file name for the INI file.

Again it will be using the applications own folder as the default destination (for the INI files).

You will need to modify the Form.cs file only.

The demo (from the link above) is easy to understand and was enough to provide me with the knowledge to create this example (and I am a C# novice).

9.
Install, from NuGet, the INI files package (in Solution Explorer, right-click on: References. Then Select: Manage NuGet Packages. Then search for: PeanutButter.INI. Install it).

10.
In your Form.cs file (Form1.cs if you have not changed the name), add the following line to the bottom of the existing using section.

using PeanutButter.INIFile;

11.
In your Form.cs file, directly under the line, public partial class Form1 : Form, add the following single line of code.

private IINIFile _loadedConfig;

It should look like the below.

public partial class Form1 : Form    {

private IINIFile _loadedConfig;

12.
On the form create two more buttons.

Button. Name: btnOpenIniFile  Text: Open INI

Button. Name: btnSaveIniFile Text: Save INI

13.
Enter the code for the Open INI buttons click event (btnOpenIniFile).

private void btnOpenIniFile_Click(object sender, EventArgs e) {        

using(OpenFileDialog OpenFileIni = new OpenFileDialog()) {
var strSettingsDirectory = Directory.GetCurrentDirectory() + "\\Settings";
System.IO.Directory.CreateDirectory(strSettingsDirectory);
OpenFileIni.InitialDirectory = strSettingsDirectory;
OpenFileIni.Filter = "INI File|*.ini";
OpenFileIni.RestoreDirectory = true;
OpenFileIni.CheckFileExists = true;
OpenFileIni.CheckPathExists = true;
OpenFileIni.Title = "Open an INI Settings File";

if (OpenFileIni.ShowDialog() == DialogResult.OK)
{
_loadedConfig = new INIFile(OpenFileIni.FileName);
txtName.Text = _loadedConfig.HasSetting("UserSettings", "txtName") ? _loadedConfig["UserSettings"]["txtName"] : "";
txtSchool.Text = _loadedConfig.HasSetting("UserSettings", "txtSchool") ? _loadedConfig["UserSettings"]["txtSchool"] : "";
txtClass.Text = _loadedConfig.HasSetting("UserSettings", "txtClass") ? _loadedConfig["UserSettings"]["txtClass"] : "";

if (_loadedConfig["UserSettings"]["chkActiveStudent"] == "Checked")
{
chkActiveStudent.Checked = true;
}
else
{
chkActiveStudent.Checked = false;
}
}
}
}

14.
Enter the code for the Save INI buttons click event (btnSaveIniFile).

private void btnSaveIniFile_Click(object sender, EventArgs e)
{
using (SaveFileDialog SaveFileIni = new SaveFileDialog())
{
var strSettingsDirectory = Directory.GetCurrentDirectory() + "\\Settings";
System.IO.Directory.CreateDirectory(strSettingsDirectory);
SaveFileIni.InitialDirectory = strSettingsDirectory;
SaveFileIni.Filter = "INI File|*.ini";
SaveFileIni.Title = "Save an INI Settings File";

if (SaveFileIni.ShowDialog() == DialogResult.OK)
{
_loadedConfig = new INIFile(SaveFileIni.FileName);
_loadedConfig["UserSettings"]["txtName"] = txtName.Text;
_loadedConfig["UserSettings"]["txtSchool"] = txtSchool.Text;
_loadedConfig["UserSettings"]["txtClass"] = txtClass.Text;

if (chkActiveStudent.Checked == true)
{
_loadedConfig["UserSettings"]["chkActiveStudent"] = "Checked";
}
else
{
_loadedConfig["UserSettings"]["chkActiveStudent"] = "UnChecked";
}

_loadedConfig.Persist();
}
}
}

15.
That’s it. Run the app.

Make some changes to the text on the textbox controls. Save them using the Save INI button.

You will be prompted for a file name. It can be anything you like (but in this example I used the name of the person I setup in the first textbox.
You do not need to enter the ini file extension. You can change the location if you wish.

Make some more changes to the text in the textBoxes but do not save them.
Click on the Open INI button. Browse to the ini file you just saved and open it.

The text you just modified, without saving, should now be changed to the text you saved into the ini file.

Save user settings for different users in WinForms?

(1) At event close main form, you call method/action save result. See How to save data when closing event happen in WinForms?

You can save it to XML file (or text file, SQL lite, SQL Server, etc), popular way is XML file(s).

Read XML file to get saved result before processing business logic in your WinForms application at Load form event or another event type at early stage of application start-up period.

(2) You also save result at previous period in config file https://stackoverflow.com/a/453230/3728901

Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file

How to save user settings programmatically?

Set

Properties.Settings.Default.myColor = Color.AliceBlue;

Get

this.BackColor = Properties.Settings.Default.myColor;

Save

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();

Reference

WinForms Application settings are not assigning

I think: something went wrong.

In Solution Explorer, double-click the .settings file. The default name for this file is Settings.settings. In the Settings designer, find the Name (MyDouble) of your setting. Each row represents a single setting.

See: Using Settings in C#.

You have:

<setting name="MyDouble" serializeAs="String">

And you write:

double myDouble = Properties.Settings.Default.MyDouble;

Convert String to double...may be it wrong?

See this page: Managing Application Settings (.NET) and this answer: What is the best way to store user settings for a .NET application?

Try this code:

Properties.Settings.Default.MyDouble = 1.5;
Properties.Settings.Default.Save();

and after it try this:

var myDouble = Properties.Settings.Default.MyDouble;

C# - How to save TextBox and CheckBox in User Settings

The first part of my answer, regarding to the fact that nothing is saved when you close your application, is based on the assumption that when testing, you leave the third textbox empty

Why is nothing saved

First is why you are seeing nothing when opening your application, leading you to believe nothing was saved when closing it.

You are in the part of your code handling what happens when your application is closing, saving all of the textboxes (and checkboxes states) in the same setting

Which leads to the following
txtBox1 contains a
txtbox2 contains nothing (or an empty string if you prefer)

When saving, what is happening with your code is that in a first step, you are putting "a" into your textbox setting.

Then, you are replacing this vlue with the content of the second textbox, which is empty

(repeat for the third textbox)

The you are saving.... An empty value.

If you wish to fix this in a "naive" way, you would need a setting per textbox and checkbox.

Which would lead to code ressembling this in your Closing event handler

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.checkBox1 = chkBox1.Checked;
Properties.Settings.Default.checkBox2 = chkBox2.Checked;
Properties.Settings.Default.checkBox3 = chkBox3.Checked;
Properties.Settings.Default.textBox1 = txtBox1.Text;
Properties.Settings.Default.textBox2 = txtBox2.Text;
Properties.Settings.Default.textBox3 = txtBox3.Text;
Properties.Settings.Default.PX = this.Location.X;
Properties.Settings.Default.PY = this.Location.Y;
Properties.Settings.Default.Save();
}

Why do I say "naive", because as you've surely understood, this approach is not sustainable for a huge number of controls, but this is not the scope of the question, I'll let you research a solution on your own for this particular point.

Why are the checkbox doing nothing to determine what is saved

First, with the events available on Winforms (at least with the .NET Framework 4.5 which I used to reproduce what you had) the only events available to be notified of the checkbox state change are :

  • CheckedChanged
  • CheckStateChanged

The first is used on a binary Checkbox (checked or not)
The second on a checkbox with an uncertain state added to both of the other states.

I imagine you used the first of the two (because that is the one used by default by Visual Studio when double clicking on it in the designer).

The first issue here is that it notifiesyou that the state changed not only that it went from unchecked to checked, but the other way around too.

That means if you only want an action to be done when checking, you need to add a.... check (an if block) to skip the cases you're not interest into.

Next is the actual saving.

What you are doing in your code is just copying the textbox values in a property in your class, and that will NOT persist after closing the application.

Now there is two approach you could use to save those values into the settings, the first is to do it as soon as you check the boxes.

What you would need to do then is for each event handler to copy the value of the textbox.... directly into the settings

An example for the first textbox and checkbox :

private void chkBox1_Checked(object sender, EventArgs e)
{
if(chkBox1.Checked)
{
Properties.Settings.Default.checkBox1 = chkBox1.Checked;
}
}

I'm not a huge fan though, and would prefer the second solution => to check in the closing event, before copying the value from the textbox into the settings, if the corresponding checkbox is closed.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.chkBox1.Checked)
{
Properties.Settings.Default.textBox = txtBox1.Text;
}
[...]
}

Now that a little better, and should be working as intended.

Please note that this answer is oriented towards correcting the problem whilst using solutions that are the closest possible of your original code.



Related Topics



Leave a reply



Submit