亲宝软件园·资讯

展开

C#实现XML文件读取 C#实现XML文件读取

Just_for_Myself 人气:0
想了解C#实现XML文件读取的相关内容吗,Just_for_Myself在本文为您仔细讲解C#实现XML文件读取的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,XML,文件读取,下面大家一起来学习吧。

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

/// <summary>
/// 工具类
/// </summary>
public static class Tools {
  /// <summary>
  /// 存储数据 UTF8
  /// </summary>
  /// <param name="data">数据,自定义类</param>
  public static void SaveData(GameData data)
  {
    string fileName = Consts.DataPath; // 文件名

    // 文件流
    Stream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
    StreamWriter sw = new StreamWriter(stream, Encoding.UTF8);     // UTF8
    XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());  // XML 文件序列化
    xmlSerializer.Serialize(sw, data);

    sw.Close();
    stream.Close();
  }

  /// <summary>
  /// 读取数据
  /// </summary>
  /// <returns>读取获得的数据</returns>
  public static GameData GetDataWithOutBom()
  {
    GameData data = new GameData();

    Stream stream = new FileStream(Consts.DataPath, FileMode.Open, FileAccess.Read);
    // 忽略标记 true
    StreamReader sr = new StreamReader(stream, true);
    XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());
    data = xmlSerializer.Deserialize(sr) as GameData;

    sr.Close();
    stream.Close();

    return data;
  }
}

加载全部内容

相关教程
猜你喜欢
用户评论