Introduction
When we write our Windows Application, we will use Settings.settings file usually. Here I want to share one small thing I ignored before so that it may save you some time.
Background
.Net empower users three configuration files: machine.config, app.config and user.config. When we use Settings.settings file in Windows Form application, we likely will miss small steps. Here are some explanation.
Set up user scoped variable
inside your visual Studio, select the property page of the Settings.setting file, you can set the user scoped variable as before:
Using the code
I created a demo application to let you display the default testSetting values and change it, then display updated value.
Here is the major code segment:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Setting1
{
public partial class Form1 : Form
{
private Properties.Settings set = Properties.Settings.Default;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
label3.Text = set.testSetting;
}
private void button2_Click(object sender, EventArgs e)
{
set.testSetting = textBox1.Text.Trim();
set.Save();
}
}
}
Next step is to press F5 and run this application. type new value( such as "this is new string") for testSetting string and save it. then click button 1 to display current value. Here we will see one question.
Question
If we open the Settings.setting file, we still see the value of testSetting is the same as we type it inside Visual Studio. Where is the new value we typed in? If we press F5 and run this demo, click display current testSetting string, the value is newly typed string. It is not in the Settings.settings file. Where is it at?
Answer
the answer is that it is saved in user.config file that reside in your local folder. on my machine, it is C:\Users\Peaker\AppData\Local\Setting1\Setting1.vshost.exe_Url_hxn3ytijneqkcgp3wnpfxrkkc2xw2hll\1.0.0.0.
the file content is below:
Lessons Learned
Default values of variables defined from Visual Studio property designer are written into applicationSettings or userSettings section of App.Config. New values of the same user scoped variables defined in runtime are written into user.config file in your local path as above example on my machine.
You are welcome to share your thoughts to improve this posting. Thank you!
History
03-12-2016 intialized this article.