这篇文章主要为大家展示了“ASP.NET中如何使用xml反序列化、缓存依赖实现个性化配置文件”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“ASP.NET中如何使用xml反序列化、缓存依赖实现个性化配置文件”这篇文章吧。
配置文件反序列化存入缓存的核心方法:
public Class.Settings GetSettings() { if (HttpRuntime.Cache["settings"] != null) return (Class.Settings)HttpRuntime.Cache["settings"]; string rootPath = GetPath(); #region rootPath if (rootPath == "") { log.Write(MsgType.Fatal, "配置文件根目录rootPath为空"); return null; } else { if (!rootPath.EndsWith("\\")) rootPath += "\\"; rootPath = rootPath + "settings\\settings.config"; } #endregion if (!File.Exists(rootPath)) { log.Write(MsgType.Fatal, "配置文件根目录rootPath为空"); return null; } string content = File.ReadAllText(rootPath, Encoding.Default); Class.Settings model = PublicMethod.XmlSerialize.DeserializeXML<Class.Settings>(content); log.Write(MsgType.Information, "读取配置文件"); CacheDependency cd = new CacheDependency(rootPath); HttpRuntime.Cache.Add("settings", model, cd, DateTime.Now.AddMinutes(5), TimeSpan.Zero, CacheItemPriority.High, null); return model; }
上面自动获取rootPath的方法:
/// <summary> /// 取当前根目录的方法 /// </summary> private static string GetPath() { string rootPath = ""; System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess(); //WebDev.WebServer visual studio web server //xxx.vhost Winform //w3wp IIS7 //aspnet_wp IIS6 //iisexpress vs2013 string processName = p.ProcessName.ToLower(); if (processName == "aspnet_wp" || processName == "w3wp" || processName == "webdev.webserver" || processName == "iisexpress") { if (System.Web.HttpContext.Current != null) rootPath = System.Web.HttpContext.Current.Server.MapPath("~/"); else //当控件在定时器的触发程序中使用时就为空 { rootPath = System.AppDomain.CurrentDomain.BaseDirectory; } } return rootPath; }
Settings实体类的定义,要注意,这里的实体类要和settings配置文件对应,否则反序列化会出错:
[XmlRoot(Namespace = "", IsNullable = false, ElementName = "settings")] public class Settings { #region 属性 [XmlElement("logger")] public LoggerConfig logger { get; set; } #endregion #region 子类 [XmlType(TypeName = "logger")] public class LoggerConfig { public string loglevel { get; set; } public string savepath { get; set; } } #endregion }
settings.config的内容实例
<?xml version='1.0' encoding='utf-8'?> <settings> <logger> <loglevel>0</loglevel> <savepath>d:\log</savepath> </logger> <queryurl>http://11.56.254.234:88/shashachaxunserver/shashachaxun</queryurl> <receiveurl>http://172.16.1.131:88/ThirdPay/ChinaUMS/xml.aspx</receiveurl> <turnurl>http://172.16.1.131:88/ThirdPay/ChinaUMS/query.aspx</turnurl> </chinaums> </settings>
以上是“ASP.NET中如何使用xml反序列化、缓存依赖实现个性化配置文件”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。