public class AppConfigSetting
{
//获取配置对象
public static AppConfig Get()
{
//尝试获取缓存中的对象
AppConfig config = (AppConfig)HttpContext.Current.Cache["AppConfig"];
//如果缓存中没有该配置对象,则直接获取对象
if (config == null)
{
//新建序列化对象并指定其类型
XmlSerializer serial = new XmlSerializer(typeof(AppConfig));
try
{
string file = HttpContext.Current.Server.MapPath(GetFile());
//读取文件流
FileStream fs = new FileStream(file, FileMode.Open);
//文件流反序列化为对象
config = (AppConfig)serial.Deserialize(fs);
fs.Close();
//将对象加入到缓存中
HttpContext.Current.Cache.Insert("AppConfig", config, new CacheDependency(file));
}
catch (System.IO.FileNotFoundException)
{
config = new AppConfig();
}
}
return config;
}
//保存配置对象
public static void Save(AppConfig config)
{
string file = HttpContext.Current.Server.MapPath(GetFile());
XmlSerializer serial = new XmlSerializer (typeof(AppConfig));
FileStream fs = new FileStream(file, FileMode.Create);
//对象序列化为文件
serial.Serialize(fs, config);
fs.Close();
}
//获取配置文件路径
private static string GetFile()
{
string path = (string)HttpContext.Current.Cache["FilePath"];
if (path == null)
{
path=ConfigurationSettings.AppSettings["AppConfigPath"];
HttpContext.Current.Cache["FilePath"] = path;
}
return path;
}
}
|