Cache緩存依賴於XML

// 此處代碼整理於博客【在.net中讀寫config文件的各種方法】的示例代碼
// http://www.cnblogs.com/fish-li/archive/2011/12/18/2292037.html


public static class XmlHelper

{
    private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
    {
        if( o == null )
            throw new ArgumentNullException("o");
        if( encoding == null )
            throw new ArgumentNullException("encoding");


        XmlSerializer serializer = new XmlSerializer(o.GetType());


        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.NewLineChars = "\r\n";
        settings.Encoding = encoding;
        settings.IndentChars = "    ";


        using( XmlWriter writer = XmlWriter.Create(stream, settings) ) {
            serializer.Serialize(writer, o);
            writer.Close();
        }
    }


    /// <summary>
    /// 將一個對象序列化爲XML字符串
    /// </summary>
    /// <param name="o">要序列化的對象</param>
    /// <param name="encoding">編碼方式</param>
    /// <returns>序列化產生的XML字符串</returns>
    public static string XmlSerialize(object o, Encoding encoding)
    {
        using( MemoryStream stream = new MemoryStream() ) {
            XmlSerializeInternal(stream, o, encoding);


            stream.Position = 0;
            using( StreamReader reader = new StreamReader(stream, encoding) ) {
                return reader.ReadToEnd();
            }
        }
    }


    /// <summary>
    /// 將一個對象按XML序列化的方式寫入到一個文件
    /// </summary>
    /// <param name="o">要序列化的對象</param>
    /// <param name="path">保存文件路徑</param>
    /// <param name="encoding">編碼方式</param>
    public static void XmlSerializeToFile(object o, string path, Encoding encoding)
    {
        if( string.IsNullOrEmpty(path) )
            throw new ArgumentNullException("path");


        using( FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write) ) {
            XmlSerializeInternal(file, o, encoding);
        }
    }


    /// <summary>
    /// 從XML字符串中反序列化對象
    /// </summary>
    /// <typeparam name="T">結果對象類型</typeparam>
    /// <param name="s">包含對象的XML字符串</param>
    /// <param name="encoding">編碼方式</param>
    /// <returns>反序列化得到的對象</returns>
    public static T XmlDeserialize<T>(string s, Encoding encoding)
    {
        if( string.IsNullOrEmpty(s) )
            throw new ArgumentNullException("s");
        if( encoding == null )
            throw new ArgumentNullException("encoding");


        XmlSerializer mySerializer = new XmlSerializer(typeof(T));
        using( MemoryStream ms = new MemoryStream(encoding.GetBytes(s)) ) {
            using( StreamReader sr = new StreamReader(ms, encoding) ) {
                return (T)mySerializer.Deserialize(sr);
            }
        }
    }


    /// <summary>
    /// 讀入一個文件,並按XML的方式反序列化對象。
    /// </summary>
    /// <typeparam name="T">結果對象類型</typeparam>
    /// <param name="path">文件路徑</param>
    /// <param name="encoding">編碼方式</param>
    /// <returns>反序列化得到的對象</returns>
    public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
    {
        if( string.IsNullOrEmpty(path) )
            throw new ArgumentNullException("path");
        if( encoding == null )
            throw new ArgumentNullException("encoding");


        string xml = File.ReadAllText(path, encoding);
        return XmlDeserialize<T>(xml, encoding);
    }
}




/// <summary>
    /// 這個類的屬性是xml的節點
    /// </summary>
    public class RunOptions
    {
        public string WebSiteUrl;
        public string UserName;


    }
    
    /// <summary>
    /// 這個類用於讀取xml的數據,並且緩存依賴
    /// </summary>
    public static class WebSiteApp
    {
        private static readonly string RunOptionsCacheKey = Guid.NewGuid().ToString();


        public static RunOptions RunOptions
        {
            get
            {
                // 首先嚐試從緩存中獲取運行參數
                RunOptions options = HttpRuntime.Cache[RunOptionsCacheKey] as RunOptions;


                if (options == null)
                {
                    // 緩存中沒有,則從文件中加載
                    string path = HttpContext.Current.Server.MapPath("~/App_Data/RunOptions.xml");
                    options = XmlHelper.XmlDeserializeFromFile<RunOptions>(path, Encoding.UTF8);


                    // 把從文件中讀到的結果放入緩存,並設置與文件的依賴關係。
                    CacheDependency dep = new CacheDependency(path);
                    // 如果您的參數較複雜,與多個文件相關,那麼也可以使用下面的方式,傳遞多個文件路徑。
                    //CacheDependency dep = new CacheDependency(new string[] { path });
                    HttpRuntime.Cache.Insert(RunOptionsCacheKey, options, dep);
                }


                return options;
            }
        }
    }
    
    
    <?xml version="1.0" encoding="utf-8"?>
<RunOptions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <WebSiteUrl>http://www.cnblogs.com/fish-li</WebSiteUrl>
  <UserName>潘繼號</UserName>
</RunOptions>




<p>WebSiteUrl: <%= WebApplication1.WebSiteApp.RunOptions.WebSiteUrl %></p>
    <p>UserName: <%= WebApplication1.WebSiteApp.RunOptions.UserName %></p>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章