📄 configfilemanage.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
namespace Utility
{
/// <summary>
/// 配置文件读写
/// </summary>
public class ConfigFileManage
{
#region App配置文件读写
/// <summary>
/// 获取App配置文件的键值,无节点则出错,出错则自动添加节点,重试即可使用
/// </summary>
/// <param name="KeyName">键名</param>
/// <returns>键值</returns>
public static string GetAppKeyValue(string KeyName)
{
try
{
return System.Configuration.ConfigurationManager.AppSettings[KeyName].ToString();
}
catch (Exception ex)
{
Pub.ShowError(ex, "System", "Pub", "GetAppKeyValue");
SetAppKeyValue(KeyName, "", "");//无节点则出错,出错则自动添加节点
return "";
}
}
/// <summary>
/// 设置App配置文件的键值(通过XML操作)
/// </summary>
/// <param name="KeyName">键名</param>
/// <param name="KeyValue">键值</param>
/// <param name="FilePath">Config文件路径,默认路径就用“”即可</param>
public static void SetAppKeyValue(string KeyName, string KeyValue, string FilePath)
{
#region 判断配置文件是否存在
if (FilePath == "")
{
FilePath = System.IO.Path.Combine(Application.StartupPath, "App.Config");
}
else if (!File.Exists(FilePath))
{
FilePath = System.IO.Path.Combine(Application.StartupPath, "App.Config");
}
if (!File.Exists(FilePath))
{
FilePath = Application.ExecutablePath + ".Config";
}
if (!File.Exists(FilePath))
{
FilePath = Pub.AppConifgName;
}
if (!File.Exists(FilePath))
{
//获取安装路径
System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
string LocalPath = asm.Location;
FilePath = System.IO.Path.Combine(Path.GetDirectoryName(LocalPath), Pub.AppConifgName);
}
//Traces(FilePath);
if (!File.Exists(FilePath))
{
return;
}
#endregion
bool BoolKeyName = false;
try
{
#region XML操作配置文件
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(FilePath);
XmlNodeList topM = xmldoc.DocumentElement.ChildNodes;
foreach (XmlElement element in topM)
{
#region 遍历节点,找到AppSeting节点
if (element.Name.ToLower() == "appsettings")
{
XmlNodeList _node = element.ChildNodes;
if (_node.Count > 0)
{
foreach (XmlNode el in _node)
{
if (el.Name[0].ToString() == "#")
{
continue;
}
if (el.Attributes["key"].InnerXml.ToLower() == KeyName.ToLower())
{
BoolKeyName = true;
el.Attributes["value"].Value = KeyValue;//此值需下次程序才生效
//如要本次就使用修改后的值,可将键值,在缓存中的AppSettings进行修改,代码如下:
System.Configuration.ConfigurationManager.AppSettings.Set(KeyName, KeyValue);
}
}
}
if (!BoolKeyName)
{
XmlElement xel = xmldoc.CreateElement("add");
xel.SetAttribute("key", KeyName);
xel.SetAttribute("value", KeyValue);
XmlNode xnode = xmldoc.SelectSingleNode("//appSettings");
xnode.AppendChild(xel);
}
}
#endregion
}
xmldoc.Save(FilePath);
#endregion
}
catch (Exception ex)
{
Pub.ShowError(ex.Message);
}
}
#endregion
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -