Use of Winform/ASP.NET app.config configuration file

introduction:

In daily development, we are used to saving the configuration information of the program in XML files, but it is not very convenient to read and write XML files in the code. Everyone must be familiar with the app.config file in the Winform/ASP.NET framework. Some automatically generated configuration information in Visual Studio is also saved in this file. Add app.config to the project, as shown below:

 

 Reading and writing the app.config file through the ConfigurationManager class is much more efficient in coding than reading and writing XML files directly.

Note that the ConfigurationManager class needs to import the package System.Configuration.ConfigurationManager:

Create the built-in node <appSettings> in the app.config file:

In the above figure, the <appSettings> node label is a built-in label. Please note that the first letter is lowercase. You can quickly locate the child nodes under the <appSettings> node through ConfigurationManager.AppSettings["UserName"].

Read node:

        private void btn_Read_Click(object sender, EventArgs e)
        {
            string userName = ConfigurationManager.AppSettings["UserName"];//读取<appSettings>节点下UserName的值
            label_Name.Text = "UserName:"+ userName;

        }

 Update node:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;

app.Settings["UserName"].Value = "Jack";//更新UserName的值
config.Save(ConfigurationSaveMode.Modified);//保存

 Add node:

app.Settings.Add("nodeName", "nodeValue"); 

A configuration file with the suffix config will be generated in the path of the exe file. Open this file in Notepad to manage the program configuration information:

 

Guess you like

Origin blog.csdn.net/weixin_40671962/article/details/119336132