Persistance en XML
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is failing Details

pull/86/head
Rémi LAVERGNE 11 months ago
parent 27fdf24e90
commit b0f608ff78
No known key found for this signature in database
GPG Key ID: CA264B55E97FD220

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
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
{
public string FileName { get; set; } = "data.xml";
public string FilePath { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
public (List<Player>, List<Game>, List<Map>, List<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);
}
public void SaveData(List<Player> players, List<Game> games, List<Map> maps, List<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));
}
}
}
}
}

@ -0,0 +1,11 @@
using Models.Game;
namespace Models.Interfaces
{
public interface IPersistence
{
(List<Player>, List<Game.Game>, List<Map>, List<BestScore>) LoadData();
void SaveData(List<Player> players, List<Game.Game> games, List<Map> maps, List<BestScore> bestScores);
}
}
Loading…
Cancel
Save