using UnityEngine; using System.Collections; using System.Xml; using System.Xml.Serialization; using System.IO; using System.Text; /// <summary> /// 持久化工具類 /// </summary> public class Persistence : MonoBehaviour { //持久化文件路徑 static string FileLocation = Application.dataPath + "//StreamingAssets//Xml//Persistence//"; /// <summary> /// 保存數據到XML /// </summary> public static void Save(string fileName, object obj){ CreateXML(fileName,SerializeObject(obj)); } /// <summary> /// 加載XML數據 /// </summary> public static object Load(string fileName, System.Type type){ return DeserializeObject(type,LoadXML(fileName)); } /// <summary> /// 序列化對象 /// </summary> public static string SerializeObject(object pObject) { string XmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlSerializer xs = new XmlSerializer(pObject.GetType()); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); xs.Serialize(xmlTextWriter, pObject); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); return XmlizedString; } /// <summary> /// 反序列化對象 /// </summary> public static object DeserializeObject(System.Type type,string pXmlizedString) { XmlSerializer xs = new XmlSerializer(type); MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); return xs.Deserialize(memoryStream); } /// <summary> /// 將二進制轉換爲字符串 /// </summary> public static string UTF8ByteArrayToString(byte[] characters) { UTF8Encoding encoding = new UTF8Encoding(); string constructedString = encoding.GetString(characters); return (constructedString); } /// <summary> /// 將字符串轉換爲二進制 /// </summary> public static byte[] StringToUTF8ByteArray(string pXmlString) { UTF8Encoding encoding = new UTF8Encoding(); byte[] byteArray = encoding.GetBytes(pXmlString); return byteArray; } /// <summary> /// 建立XML文件 /// </summary> public static void CreateXML(string fileName,string dataStr) { StreamWriter writer; FileInfo t = new FileInfo(FileLocation+"//"+ fileName + ".xml"); if(!t.Exists){ writer = t.CreateText(); }else{ t.Delete(); writer = t.CreateText(); } writer.Write(dataStr); writer.Close(); } /// <summary> ///加載XML文件 /// </summary> public static string LoadXML(string fileName) { StreamReader r = File.OpenText(FileLocation+"//"+ fileName + ".xml"); string info = r.ReadToEnd(); r.Close(); return info; } }