C# 程序配置文件封装操作类
封装类
internal class AppConfig
{
private static ConfigAppSetting m_AppSettings;
private static ConfigConnectionStrings m_ConnectionStrings;
public static ConfigAppSetting AppSettings
{
get
{
if (m_AppSettings == null)
{
m_AppSettings = new ConfigAppSetting();
m_AppSettings.AppSettingChanged += OnAppSettingChanged;
}
return m_AppSettings;
}
}
public static ConfigConnectionStrings ConnectionStrings
{
get
{
if (m_ConnectionStrings == null)
{
m_ConnectionStrings = new ConfigConnectionStrings();
m_ConnectionStrings.ConnectionStringsChanged += OnConnectionStringsChanged;
}
return m_ConnectionStrings;
}
}
private static void OnAppSettingChanged(string name, string value)
{
string configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
if (!System.IO.File.Exists(configPath))
{
const string content = @"<?xml version=""1.0""?><configuration></configuration>";
System.IO.File.WriteAllText(configPath, content, Encoding.UTF8);
}
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(configPath);
System.Xml.XmlNode nodeConfiguration = doc.SelectSingleNode(@"configuration");
if (nodeConfiguration == null)
{
nodeConfiguration = doc.CreateNode(System.Xml.XmlNodeType.Element, "configuration", string.Empty);
doc.AppendChild(nodeConfiguration);
}
System.Xml.XmlNode nodeAppSettings = nodeConfiguration.SelectSingleNode(@"appSettings");
if (nodeAppSettings == null)
{
nodeAppSettings = doc.CreateNode(System.Xml.XmlNodeType.Element, "appSettings", string.Empty);
if (!nodeConfiguration.HasChildNodes)
nodeConfiguration.AppendChild(nodeAppSettings);
else
{
//configSections 必须放在 第一个, 所以得 避开 configSections
System.Xml.XmlNode firstNode = nodeConfiguration.ChildNodes[0];
bool firstNodeIsSections = string.Equals(firstNode.Name, "configSections", StringComparison.CurrentCultureIgnoreCase);
if (firstNodeIsSections)
nodeConfiguration.InsertAfter(nodeAppSettings, firstNode);
else
nodeConfiguration.InsertBefore(nodeAppSettings, firstNode);
}
}
string xmlName = FormatXmlStr(name);
System.Xml.XmlNode nodeAdd = nodeAppSettings.SelectSingleNode(@"add[@key='" + xmlName + "']");
if (nodeAdd == null)
{
nodeAdd = doc.CreateNode(System.Xml.XmlNodeType.Element, "add", string.Empty);
nodeAppSettings.AppendChild(nodeAdd);
}
System.Xml.XmlElement nodeElem = (System.Xml.XmlElement)nodeAdd;
nodeElem.SetAttribute("key", name);
nodeElem.SetAttribute("value", value);
doc.Save(configPath);
try { System.Configuration.ConfigurationManager.RefreshSection("appSettings"); } catch (Exception) { }
}
private static void OnConnectionStringsChanged(string name, string value)
{
string configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
if (!System.IO.File.Exists(configPath))
{
const string content = @"<?xml version=""1.0""?><configuration></configuration>";
System.IO.File.WriteAllText(configPath, content, Encoding.UTF8);
}
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(configPath);
System.Xml.XmlNode nodeConfiguration = doc.SelectSingleNode(@"configuration");
if (nodeConfiguration == null)
{
nodeConfiguration = doc.CreateNode(System.Xml.XmlNodeType.Element, "configuration", string.Empty);
doc.AppendChild(nodeConfiguration);
}
System.Xml.XmlNode nodeAppSettings = nodeConfiguration.SelectSingleNode(@"appSettings");
System.Xml.XmlNode nodeConnectionStrings = nodeConfiguration.SelectSingleNode(@"connectionStrings");
if (nodeConnectionStrings == null)
{
nodeConnectionStrings = doc.CreateNode(System.Xml.XmlNodeType.Element, "connectionStrings", string.Empty);
if (!nodeConfiguration.HasChildNodes)
nodeConfiguration.AppendChild(nodeConnectionStrings);
else
{
//优先将 connectionStrings 放在 appSettings 后面
if (nodeAppSettings != null)
nodeConfiguration.InsertAfter(nodeConnectionStrings, nodeAppSettings);
else
{
//如果 没有 appSettings 节点, 则 configSections 必须放在 第一个, 所以得 避开 configSections
System.Xml.XmlNode firstNode = nodeConfiguration.ChildNodes[0];
bool firstNodeIsSections = string.Equals(firstNode.Name, "configSections", StringComparison.CurrentCultureIgnoreCase);
if (firstNodeIsSections)
nodeConfiguration.InsertAfter(nodeConnectionStrings, firstNode);
else
nodeConfiguration.InsertBefore(nodeConnectionStrings, firstNode);
}
}
}
string xmlName = FormatXmlStr(name);
System.Xml.XmlNode nodeAdd = nodeConnectionStrings.SelectSingleNode(@"add[@name='" + xmlName + "']");
if (nodeAdd == null)
{
nodeAdd = doc.CreateNode(System.Xml.XmlNodeType.Element, "add", string.Empty);
nodeConnectionStrings.AppendChild(nodeAdd);
}
System.Xml.XmlElement nodeElem = (System.Xml.XmlElement)nodeAdd;
nodeElem.SetAttribute("name", name);
nodeElem.SetAttribute("connectionString", value);
doc.Save(configPath);
try
{
System.Configuration.ConfigurationManager.RefreshSection("connectionString"); //RefreshSection 无法刷新 connectionString 节点
System.Reflection.FieldInfo fieldInfo = typeof(System.Configuration.ConfigurationManager).GetField("s_initState", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (fieldInfo != null) fieldInfo.SetValue(null, 0); //将配置文件 设置为: 未分析 状态, 配置文件 将会在下次读取 时 重新分析.
}
catch (Exception) { }
}
private static string FormatXmlStr(string value)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
string result = value.Replace("<", "<").Replace(">", ">").Replace("&", "&").Replace("'", "'").Replace("\"", """);
return result;
//< < 小于号
//> > 大于号
//& & 和
//' ' 单引号
//" " 双引号
}
public class ConfigAppSetting
{
private readonly InnerIgnoreDict<string> m_Hash = new InnerIgnoreDict<string>();
public string this[string name]
{
get
{
string value = m_Hash[name];
if (string.IsNullOrWhiteSpace(value))
{
try { value = System.Configuration.ConfigurationManager.AppSettings[name]; } catch (Exception) { }
m_Hash[name] = value;
return value;
}
return value;
}
set
{
m_Hash[name] = value;
try { System.Configuration.ConfigurationManager.AppSettings[name] = value; } catch (Exception) { }
if (AppSettingChanged != null) AppSettingChanged(name, value);
}
}
public AppSettingValueChanged AppSettingChanged;
public delegate void AppSettingValueChanged(string name, string value);
}
public class ConfigConnectionStrings
{
private readonly InnerIgnoreDict<System.Configuration.ConnectionStringSettings> m_Hash = new InnerIgnoreDict<System.Configuration.ConnectionStringSettings>();
public string this[string name]
{
get
{
System.Configuration.ConnectionStringSettings value = m_Hash[name];
if (value == null || string.IsNullOrWhiteSpace(value.ConnectionString))
{
try { value = System.Configuration.ConfigurationManager.ConnectionStrings[name]; } catch (Exception) { }
m_Hash[name] = value;
return value == null ? string.Empty : value.ConnectionString;
}
return value.ConnectionString;
}
set
{
System.Configuration.ConnectionStringSettings setting = new System.Configuration.ConnectionStringSettings();
setting.Name = name;
setting.ConnectionString = value;
m_Hash[name] = setting;
//try { ConfigurationManager.ConnectionStrings[name] = setting; } catch (Exception) { }
if (ConnectionStringsChanged != null) ConnectionStringsChanged(name, value);
}
}
public ConnectionStringsValueChanged ConnectionStringsChanged;
public delegate void ConnectionStringsValueChanged(string name, string value);
}
private class InnerIgnoreDict<T> : Dictionary<string, T>
{
public InnerIgnoreDict() : base(StringComparer.CurrentCultureIgnoreCase)
{
}
#if (!WindowsCE && !PocketPC)
public InnerIgnoreDict(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
#endif
private readonly object getSetLocker = new object();
private static readonly T defaultValue = default(T);
public new T this[string key]
{
get
{
if (key == null) return defaultValue;
lock (getSetLocker) //为了 多线程的 高并发, 取值也 加上 线程锁
{
T record;
if (TryGetValue(key, out record)) return record;
else return defaultValue;
}
}
set
{
try
{
if (key != null)
{
lock (getSetLocker)
{
//if (!value.Equals(default(T)))
//{
if (base.ContainsKey(key)) base[key] = value;
else base.Add(key, value);
//}
//else
//{
// base.Remove(key);
//}
}
}
}
catch (Exception) { }
}
}
}
public static Dictionary<string, string> ParseString(string String)
{
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
string[] Projects = String.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in Projects)
{
string[] pro = item.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
if (pro.Length == 2)
{
myDictionary.Add(pro[0], pro[1]);
}
}
return myDictionary;
}
}
读
string str = AppConfig.ConnectionStrings["ThirdPartyAccounts"];
写
AppConfig.ConnectionStrings["ThirdPartyAccounts"] = "ThirdPartyAccounts";
//网络素材仅限收藏 方便学习