?? 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 + -