动态读取文件中的资源

我一直在使用resx文件作为静态字符串,以便有一个更改它们的中心位置。 问题是我在构建和部署项目后无法更改它们。

在部署之后,我想要更改一些字符串,而不重新启动进程(因此.config文件已经用完)。

可以编写有效解析配置文件(XML / JSON / YAML /?)的代码,例如将结果缓存X秒或使用FileSystemWatcher监视它的变化,但是已经完成了这样的事情?

编辑:使用Json.NET和Rashmi Pandit指向CacheDependency的指针我编写了这个JSON解析类,它缓存解析后的结果直到文件被更改:

 public class CachingJsonParser { public static CachingJsonParser Create() { return new CachingJsonParser( HttpContext.Current.Server, HttpContext.Current.Cache); } private readonly HttpServerUtility _server; private readonly Cache _cache; public CachingJsonParser(HttpServerUtility server, Cache cache) { _server = server; _cache = cache; } public T Parse(string relativePath) { var cacheKey = "cached_json_file:" + relativePath; if (_cache[cacheKey] == null) { var mappedPath = _server.MapPath(relativePath); var json = File.ReadAllText(mappedPath); var result = JavaScriptConvert.DeserializeObject(json, typeof(T)); _cache.Insert(cacheKey, result, new CacheDependency(mappedPath)); } return (T)_cache[cacheKey]; } } 

用法

JSON文件:

 { "UserName": "foo", "Password": "qwerty" } 

对应的数据类:

 class LoginData { public string UserName { get; set; } public string Password { get; set; } } 

解析和缓存:

 var parser = CachingJsonParser.Create(); var data = parser.Parse("~/App_Data/login_data.json"); 

您可以使用xml文件并将其存储在缓存中。 当对文件进行任何更改时,您可以使用CacheDependency重新加载缓存。 链接: CacheDependency : CacheItemUpdateCallback :

在您的情况下,您的缓存应该存储XmlDocument作为值

编辑:这是我的示例代码

 protected void Page_Load(object sender, EventArgs e) { XmlDocument permissionsDoc = null; if (Cache["Permissions"] == null) { string path = Server.MapPath("~/XML/Permissions.xml"); permissionsDoc = new XmlDocument(); permissionsDoc.Load(Server.MapPath("~/XML/Permissions.xml")); Cache.Add("Permissions", permissionsDoc, new CacheDependency(Server.MapPath("~/XML/Permissions.xml")), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, new CacheItemRemovedCallback(ReloadPermissionsCallBack)); } else { permissionsDoc = (XmlDocument)Cache["Permissions"]; } } private void ReloadPermissionsCallBack(string key, object value, CacheItemRemovedReason reason) { XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("~/XML/Permissions.xml")); Cache.Insert("Permissions", doc , new CacheDependency(Server.MapPath("~/XML/Permissions.xml")), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, new CacheItemRemovedCallback(ReloadPermissionsCallBack)); }