Examples of reading and writing Config files in ASP. NET
- 2021-10-11 18:07:04
- OfStack
This article mainly introduces the related contents of Config reading and writing examples in ASP. NET, and shares them for your reference and study. Not much to say, let's take a look at the detailed introduction.
The method is as follows:
If it is an WinForm program, you need to add a reference:
System.ServiceModel System.ConfigurationApp.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>
/// Return *.exe.config In a file appSettings Configure section's value Items
///</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>
/// In *.exe.config In a file appSettings Configuration section increase 1 Pair key-value pair
///</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 the example
ConfigHelper.GetAppConfig("testkey")
Write an example
ConfigHelper.UpdateAppConfig("testkey", "abc");
Summarize