You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Trek-12/source/Trek-12/DataContractPersistence/DataContractXml.cs

82 lines
3.0 KiB

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;
using Models.Game;
using Models.Interfaces;
namespace DataContractPersistence
{
public class DataContractXml : IPersistence
{
/// <summary>
/// Name of the file where the data will be saved
/// </summary>
public string FileName { get; set; } = "data.xml";
/// <summary>
/// Path (relative to the project)
/// </summary>
public string FilePath { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Trek_12");
/// <summary>
/// Load all the data from XML file
/// </summary>
/// <returns>A tuple with the lists of players, games, maps and best scores</returns>
public (ObservableCollection<Player>, ObservableCollection<Game>, ObservableCollection<Map>, ObservableCollection<BestScore>) LoadData()
{
var serializer = new DataContractSerializer(typeof(DataToPersist));
DataToPersist? data = new DataToPersist();
using (Stream s = File.OpenRead(Path.Combine(FilePath, FileName)))
{
data = serializer.ReadObject(s) as DataToPersist;
}
Console.WriteLine("Data loaded: " + Path.Combine(FilePath, FileName));
return (data.Players, data.Games, data.Maps, data.BestScores);
}
/// <summary>
/// Save all the data to a XML file
/// </summary>
/// <param name="players"></param>
/// <param name="games"></param>
/// <param name="maps"></param>
/// <param name="bestScores"></param>
public void SaveData(ObservableCollection<Player> players, ObservableCollection<Game> games, ObservableCollection<Map> maps, ObservableCollection<BestScore> bestScores)
{
if(!Directory.Exists(FilePath))
{
Debug.WriteLine("Directory created");
Debug.WriteLine(Directory.GetDirectoryRoot(FilePath));
Debug.WriteLine(FilePath);
Directory.CreateDirectory(FilePath);
}
var serializer = new DataContractSerializer(typeof(DataToPersist));
DataToPersist? data = new DataToPersist();
data.Players = players;
data.Games = games;
data.Maps = maps;
data.BestScores = bestScores;
var settings = new XmlWriterSettings() { Indent = true };
using (TextWriter tw = File.CreateText(Path.Combine(FilePath, FileName)))
{
using (XmlWriter writer = XmlWriter.Create(tw, settings))
{
serializer.WriteObject(writer, data);
Console.WriteLine("Data saved: " + Path.Combine(FilePath, FileName));
}
}
}
}
}