private static object obj = new object();
private NameValueCollection _system = null;
/// <summary>
/// 得到系统配置表信息
/// </summary>
/// <returns>NameValueCollection 对象</returns>
public NameValueCollection GetSystem()
{
lock (obj)
{
if (_system == null)
{
if (HttpContext.Current == null || HttpContext.Current.Cache == null || HttpContext.Current.Cache["system"] == null)
{
//read xml
string path = AppDomain.CurrentDomain.BaseDirectory + "config\\data.config";
initSystemConfig();
NameValueCollection nvc = new NameValueCollection();
XmlDocument Doc_Detail = new XmlDocument();
Doc_Detail.Load((path));
XmlNodeList NodeList = Doc_Detail.SelectNodes("/root/system/*");
if (NodeList.Count > 0)
{
for (int i = 0; i < NodeList.Count; i++)
{
if (NodeList[i] != null)
{
nvc.Add(NodeList[i].Name, NodeList[i].InnerText);
}
}
}
_system = nvc;
if (HttpContext.Current != null)
HttpContext.Current.Cache.Add("system", nvc, new System.Web.Caching.CacheDependency(HttpContext.Current.Server.MapPath("/config/data.config")), System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
}
else
{
_system = (NameValueCollection)HttpContext.Current.Cache["system"];
}
}
}
return _system;
}
/// <summary>
/// 初始化文件信息
/// </summary>
private void initSystemConfig()
{
string path1 = AppDomain.CurrentDomain.BaseDirectory+"config";
if (!Directory.Exists(path1))
{
Directory.CreateDirectory(path1);
}
string path = AppDomain.CurrentDomain.BaseDirectory+"config\\data.config";
FileInfo CreateFile = new FileInfo(path); //创建文件
if (!CreateFile.Exists)
{
FileStream FS = CreateFile.Create();
FS.Close();
StreamWriter SW;
SW = File.AppendText(path);
SW.WriteLine("<?xml version=\"1.0\"?><root><system></system></root>");
SW.Close();
}
}
//知识点:
//NameValueCollection 作为键值对存储数据
//xmlDoc.SelectNodes("/root/system/*"); 以反斜杠"/"分开得到可以 XmlNodeList 列表。