1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Linq;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.HtmlControls;
9 using System.Web.UI.WebControls;
10 using System.Web.UI.WebControls.WebParts;
11 using System.Xml.Linq;
12 using System.IO;
13 using System.Xml.Serialization;
14
15 namespace Taotao.Test.Config
16 {
17 /// <summary>
18 /// 系统配置
19 /// </summary>
20 public class SystemConfig
21 {
22 /// <summary>
23 /// 文件路径
24 /// </summary>
25 private static string filePath;
26 /// <summary>
27 /// 配置对象
28 /// </summary>
29 private static SystemConfigInfo systemConfigInfo;
30 /// <summary>
31 /// 锁对象
32 /// </summary>
33 private static readonly object lockObj = new object();
34 /// <summary>
35 /// 文件最后修改时间
36 /// </summary>
37 private static DateTime fileLastChangeTime;
38
39 static SystemConfig()
40 {
41 filePath = HttpContext.Current.Server.MapPath("~/Config/SystemConfig.config");
42 fileLastChangeTime = File.GetLastWriteTime(filePath);
43 systemConfigInfo = GetConfig();
44 }
45
46 /// <summary>
47 /// 获取配置对象实例
48 /// </summary>
49 /// <returns></returns>
50 public static SystemConfigInfo GetConfig()
51 {
52 DateTime newFileLastChangeTime = File.GetLastWriteTime(filePath);
53 //配置文件被修改
54 if (newFileLastChangeTime != fileLastChangeTime)
55 {
56 systemConfigInfo = (SystemConfigInfo)DeSerialize(typeof(SystemConfigInfo), filePath);
57 }
58 else
59 {
60 if (systemConfigInfo == null)
61 {
62 lock (lockObj)
63 {
64 if (systemConfigInfo == null)
65 {
66 systemConfigInfo = (SystemConfigInfo)DeSerialize(typeof(SystemConfigInfo), filePath);
67 }
68 }
69 }
70 }
71
72 return systemConfigInfo;
73 }
74
75 /// <summary>
76 /// 将配置文件内容发序列化成对象
77 /// </summary>
78 /// <param name="type"></param>
79 /// <param name="filePath"></param>
80 /// <returns></returns>
81 private static object DeSerialize(Type type, string filePath)
82 {
83 try
84 {
85 using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
86 {
87 XmlSerializer xs = new XmlSerializer(type);
88 return xs.Deserialize(fs);
89 }
90 }
91 catch (Exception ex)
92 {
93 throw ex;
94 }
95 }
96 }
97 }