C# 调用APP.config配置文件
1.编写需要的参数
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Text" value="参数1"/>
</appSettings>
</configuration>
2.单独调用其中的一个参数
//读取参数
string? str = ConfigurationManager.AppSettings["Text"];
//写入参数
ConfigurationManager.AppSettings["Text"] = "参数2";
3.编写帮助函数
/// <summary>
/// 获取配置文件中的值
/// </summary>
/// <param name="key">配置文件的key值</param>
/// <returns></returns>
public static string GetConfigValue(string key)
{
string strValue = string.Empty;
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] != null)
{
return config.AppSettings.Settings[key].Value;
}
}
catch (Exception)
{
//ex.Message.Error();
}
return strValue;
}
/// <summary>
/// 设置配置文件中的值
/// </summary>
/// <param name="strKey">配置文件的key值</param>
/// <param name="strValue">配置文件的value值</param>
public static void SetConfigValue(string strKey, string strValue)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[strKey] != null)
{
config.AppSettings.Settings[strKey].Value = strValue;
}
else
{
config.AppSettings.Settings.Add(strKey, strValue);
}
config.Save(ConfigurationSaveMode.Modified);
}
catch (Exception)
{
//ex.Message.Error();
}
}
4.注意
更新之后的参数会立即生效不需要重启也可以读取到想要的参数.
2022/10/25