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;
}
}
}
Windows phone IsolatedStorageFile 读写XML
最新推荐文章于 2017-11-14 22:06:00 发布