Usually during the .NET development process, we will come into contact with two types of configuration files: config files and xml files. The following article mainly introduces you to the relevant information about the reading and writing of Config files in ASP.NET. In the article The introduction through the sample code is very detailed. Friends in need can refer to it. Let’s take a look together.
This article mainly introduces to you the relevant content about the Config reading and writing examples in ASP.NET, and shares it for your reference and study. Without further ado, let’s take a look at the detailed introduction.
The method is as follows:
If it is a WinForm program, you need to add a reference:
System. ServiceModel
System.Configuration
App.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="testkey" value="0"></add> </appSettings> </configuration>
NetUtilityLib
using System.Configuration; namespace pcauto { public static class ConfigHelper { ///<summary> ///返回*.exe.config文件中appSettings配置节的value项 ///</summary> ///<param name="strKey"></param> ///<returns></returns> public static string GetAppConfig(string strKey) { string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == strKey) { return config.AppSettings.Settings[strKey].Value.ToString(); } } return null; } ///<summary> ///在*.exe.config文件中appSettings配置节增加一对键值对 ///</summary> ///<param name="newKey"></param> ///<param name="newValue"></param> public static void UpdateAppConfig(string newKey, string newValue) { string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); bool exist = false; foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == newKey) { exist = true; } } if (exist) { config.AppSettings.Settings.Remove(newKey); } config.AppSettings.Settings.Add(newKey, newValue); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } } }
Read example
ConfigHelper.GetAppConfig("testkey")
Write Example
ConfigHelper.UpdateAppConfig("testkey", "abc");
Summary
The above is the detailed content of Example sharing on how to read and write Config files in ASP.NET. For more information, please follow other related articles on the PHP Chinese website!