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.

72 lines
1.9 KiB

using Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace XmlData
{
public class XmlDataManager : IDataManager
{
string xmlFile = "nounours.xml";
public XmlDataManager()
{
var projDir = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).FullName, GetType().GetTypeInfo().Assembly.GetName().Name);
var dir = Path.Combine(projDir.ToString(), "XML");
Directory.SetCurrentDirectory(dir);
}
DataContractSerializer Serializer { get; set; } = new DataContractSerializer(typeof(List<Nounours>));
public IEnumerable<Nounours> LesNounours
{
get
{
using (Stream s = File.OpenRead(xmlFile))
{
lesNounours = Serializer.ReadObject(s) as List<Nounours>;
}
return lesNounours.AsReadOnly();
}
}
private List<Nounours> lesNounours = new List<Nounours>();
public void Add(Nounours nounours)
{
if (lesNounours.Contains(nounours)) return;
lesNounours.Add(nounours);
SaveChanges();
}
public void Remove(Nounours nounours)
{
lesNounours.Remove(nounours);
SaveChanges();
}
public void Update(Nounours nounours)
{
if (!lesNounours.Contains(nounours)) return;
lesNounours.Remove(nounours);
lesNounours.Add(nounours);
SaveChanges();
}
private void SaveChanges()
{
using (Stream s = File.Create(xmlFile))
{
Serializer.WriteObject(s, lesNounours);
}
}
}
}