您的位置:首页 > 其它

Windows phone IsolatedStorageFile 读写XML

2014-04-25 15:51 218 查看
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息