1 using System.Collections; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Text; 5 using System.Xml.Serialization; 6 7 /// <summary> 8 /// 工具類 9 /// </summary> 10 public static class Tools { 11 /// <summary> 12 /// 存儲數據 UTF8 13 /// </summary> 14 /// <param name="data">數據,自定義類</param> 15 public static void SaveData(GameData data) 16 { 17 string fileName = Consts.DataPath; // 文件名 18 19 // 文件流 20 Stream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); 21 StreamWriter sw = new StreamWriter(stream, Encoding.UTF8); // UTF8 22 XmlSerializer xmlSerializer = new XmlSerializer(data.GetType()); // XML 文件序列化 23 xmlSerializer.Serialize(sw, data); 24 25 sw.Close(); 26 stream.Close(); 27 } 28 29 /// <summary> 30 /// 讀取數據 31 /// </summary> 32 /// <returns>讀取獲得的數據</returns> 33 public static GameData GetDataWithOutBom() 34 { 35 GameData data = new GameData(); 36 37 Stream stream = new FileStream(Consts.DataPath, FileMode.Open, FileAccess.Read); 38 // 忽略標記 true 39 StreamReader sr = new StreamReader(stream, true); 40 XmlSerializer xmlSerializer = new XmlSerializer(data.GetType()); 41 data = xmlSerializer.Deserialize(sr) as GameData; 42 43 sr.Close(); 44 stream.Close(); 45 46 return data; 47 } 48 }