48 lines
1.4 KiB
C#
48 lines
1.4 KiB
C#
using FileImplements.Models;
|
|
using System.Xml.Linq;
|
|
|
|
namespace FileImplements
|
|
{
|
|
public class DataFileSingleton
|
|
{
|
|
private static DataFileSingleton? instance;
|
|
|
|
private readonly string KeyFileName = "Key.xml";
|
|
private readonly string CertFileName = "Cert.xml";
|
|
public List<Key> Keys { get; private set; }
|
|
public List<Cert> Certs { get; private set; }
|
|
public static DataFileSingleton GetInstance()
|
|
{
|
|
if (instance == null)
|
|
{
|
|
instance = new DataFileSingleton();
|
|
}
|
|
return instance;
|
|
}
|
|
public void SaveKeys() => SaveData(Keys, KeyFileName, "Keys", x => x.GetXElement);
|
|
public void SaveCerts() => SaveData(Certs, CertFileName, "Certs", x => x.GetXElement);
|
|
private DataFileSingleton()
|
|
{
|
|
Keys = LoadData(KeyFileName, "Keys", x => Key.Create(x)!)!;
|
|
Certs = LoadData(CertFileName, "Certs", x => Cert.Create(x)!)!;
|
|
}
|
|
|
|
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
|
|
{
|
|
if (File.Exists(filename))
|
|
{
|
|
return XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
|
|
}
|
|
|
|
return new List<T>();
|
|
}
|
|
|
|
private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> selectFunction)
|
|
{
|
|
if (data != null)
|
|
{
|
|
new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename);
|
|
}
|
|
}
|
|
}
|
|
} |