.net ConfigurationManager.AppSettings[key];读取配置文件,依赖于.net framework 库,当升级为.net core 时会读不到,此时
.net core 读取配置文件,可以直接通过读取xml节点
点击查看代码
public class Configs
{
/// <summary>
/// 根据Key取Value值(弃用)
/// </summary>
/// <param name="key"></param>
public static string GetValue(string key)
{
object rel = ConfigurationManager.AppSettings[key];
return (rel == null)?string.Empty:rel.ToString().Trim();
}
/// <summary>
/// 根据Key取Value值
/// </summary>
/// <param name="key"></param>
public static string GetSysConfigValue(string key)
{
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
var configPath = System.IO.Directory.GetCurrentDirectory() + "/Configs/system.config";
// xDoc.Load(HttpContext.Current.Server.MapPath("~/Configs/system.config"));
xDoc.Load(configPath);
XmlNodeList adds = xDoc.SelectNodes("//appSettings/add");
foreach (XmlNode item in adds)
{
var keyStr = item.Attributes[0].Value;
var valueStr = item.Attributes[1].Value;
if (keyStr == key)
{
return valueStr;
}
}
return string.Empty;
}
/// <summary>
/// 根据Key修改Value
/// </summary>
/// <param name="key">要修改的Key</param>
/// <param name="value">要修改为的值</param>
public static void SetValue(string key, string value)
{
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
var configPath = System.IO.Directory.GetCurrentDirectory() + "/Configs/system.config";
// xDoc.Load(HttpContext.Current.Server.MapPath("~/Configs/system.config"));
xDoc.Load(configPath);
System.Xml.XmlNode xNode;
System.Xml.XmlElement xElem1;
System.Xml.XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
if (xElem1 != null)
{
xElem1.SetAttribute("value", value);
}
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", key);
xElem2.SetAttribute("value", value);
xNode.AppendChild(xElem2);
}
//xDoc.Save(HttpContext.Current.Server.MapPath("~/Configs/system.config"));
xDoc.Save(configPath);
ConfigurationManager.RefreshSection("appSettings");
}
}