XmlSerializationHelper Xml序列化工具

把對象序列化成 xml文件,只能對簡單實體類對象序列化哦



    /// <summary>
    /// XmlSerializationHelper Xml序列化工具
    /// </summary>
    public class XmlSerializationHelper
    {
        #region --- Functions Begin ---

        /// <summary>
        /// 從Xml文檔讀取獲得對象
        /// </summary>
        /// <typeparam name="T">對象類</typeparam>
        /// <param name="fileFullPath">xml文件完整路徑</param>
        /// <returns>對象實體,失敗拋出異常</returns>
        public static T LoadXmlFile<T>(string fileFullPath) where T : new()
        {
            FileStream fs = null;

            try
            {
                fs = new FileStream(fileFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer xml = new XmlSerializer(typeof(T));
                return (T)xml.Deserialize(fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

        /// <summary>
        /// 保存對象到Xml文檔
        /// </summary>
        /// <typeparam name="T">對象類</typeparam>
        /// <param name="t">對象</param>
        /// <param name="fileFullPath">xml文件完整路徑</param>
        /// <returns>成功返回 True 拋出異常</returns>
        public static bool Save<T>(T t, string fileFullPath) where T : new()
        {
            bool bl = false;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileFullPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);

                XmlSerializer xml = new XmlSerializer(typeof(T));
                xml.Serialize(fs, t);
                bl = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
            return bl;
        }
        #endregion --- Functions End ---
    }




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章