您应该缓存文件并实现 CacheDependency,以便如果对文件进行任何更改,文件就会重新加载到缓存中。我在我的应用程序中使用了一个权限 xml 文件,该文件存储在缓存中,并在文件被更改时重新加载。这是代码:
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));
}
缓存还将提高您的应用程序性能。