C# XML文件读取

 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 }

 

posted @ 2018-04-08 16:00  Just_for_Myself  阅读(1097)  评论(0编辑  收藏  举报