public static void SetAppConfig<T>(string appKey, T value, string description = "")
{
string appValue = "";
Type t = typeof(T);
if (t.Name == "Boolean")
{
appValue = bool.Parse(value.ToString()) ? "1" : "0";
}
else if (t.IsEnum)
{
appValue = Convert.ToInt32(value).ToString();
}
else
{
appValue = value.ToString();
}
XmlDocument xDoc = new XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
XmlNode xNode = xDoc.SelectSingleNode("//appSettings");
var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
if (xElem != null)
{
xElem.SetAttribute("value", appValue);
}
else
{
if (!string.IsNullOrWhiteSpace(description))
{
XmlComment comment = xDoc.CreateComment(description);
xNode.AppendChild(comment);
}
var xNewElem = xDoc.CreateElement("add");
xNewElem.SetAttribute("key", appKey);
xNewElem.SetAttribute("value", appValue);
xNode.AppendChild(xNewElem);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}
C# 保存配置文件,不存在则创建
Guess you like
Origin blog.csdn.net/qq_38341160/article/details/121903490
Ranking