Windows phone IsolatedStorageFile 读写XML

来源:互联网 发布:世界经济数据 编辑:程序博客网 时间:2024/06/10 12:55
using System;using System.IO;using System.IO.IsolatedStorage;using System.Xml;using System.Xml.Serialization;namespace CommonUI.CommonHelper{    public static class IsolatedStorageFileHelper    {        private const string CONFIG_NAME = "Config.xml";        private static bool CheckStoreConfigExist()        {            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())            {                return isolatedStorage.FileExists(CONFIG_NAME);            }        }        /// <summary>        /// Save data to XML file        /// </summary>        /// <typeparam name="T">the type to save</typeparam>        /// <param name="t">the data the save</param>        public static void CreateStoreConifgXML<T>(T t)        {            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())            {                // Write to the Isolated Storage                XmlWriterSettings settings = new XmlWriterSettings();                settings.Indent = true;                if (CheckStoreConfigExist())                {                    isolatedStorage.DeleteFile(CONFIG_NAME);                }                using (IsolatedStorageFileStream isoStream = isolatedStorage.CreateFile(CONFIG_NAME))                {                    XmlSerializer serializer = new XmlSerializer(typeof(T));                    using (XmlWriter xmlWriter = XmlWriter.Create(isoStream, settings))                    {                        serializer.Serialize(xmlWriter, t);                    }                }            }        }        /// <summary>        /// Read data from config        /// </summary>        /// <typeparam name="T">the type to get</typeparam>        /// <returns>the data get</returns>        public static T GetDataFromConifgXML<T>(T t)        {            T result = default(T);            try            {                using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())                {                    if (!CheckStoreConfigExist())                    {                        return result;                    }                    using (IsolatedStorageFileStream isoStream = isolatedStorage.OpenFile(CONFIG_NAME, FileMode.Open))                    {                        using (StreamReader reader = new StreamReader(isoStream))                        {                            XmlSerializer serializer = new XmlSerializer(typeof(T));                            result = (T)serializer.Deserialize(reader);                        }                    }                }            }            catch (Exception isoException)            {                //Nothing to do, only to prevent app crash here.            }            return result;        }    }}

0 0