using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Xml;
using System.Net.Sockets;
using XYLEM.Base.Files;
namespace XYLEM.Base.XML
{
internal class XMLWriteFuncClass
{
///
/// Writes the given object instance to an XML file.
/// Only Public properties and variables will be written to the file. These can be any type though, even other classes.
/// If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.
/// Object type must have a parameterless constructor.
///
/// The type of object being written to the file.
/// The file path to write the object instance to.
/// The object instance to write to the file.
/// If false the file will be overwritten if it already exists. If true the contents will be appended to the file.
public static void WriteToXmlFile(string filePath, T objectToWrite, bool append = false) where T : new()
{
// from https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
TextWriter writer = null;
try
{
writer = new StreamWriter(filePath, append);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(writer, objectToWrite);
}
catch (Exception ex)
{
throw new Exception(ex.ToFuncErrorText(typeof(XMLWriteFuncClass).ToString(), ProgramLogCSVFileClass.GetCurrentStaticMethod()));
}
finally
{
if (writer != null)
writer.Close();
}
}
///
/// Reads an object instance from an XML file.
/// Object type must have a parameterless constructor.
///
/// The type of object to read from the file.
/// The file path to read the object instance from.
/// Returns a new instance of the object read from the XML file.
public static T ReadFromXmlFile(string filePath) where T : new()
{
// from https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
TextReader reader = null;
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)xmlSerializer.Deserialize(reader);
}
catch (Exception ex)
{
throw new Exception(ex.ToFuncErrorText(typeof(XMLWriteFuncClass).ToString(), ProgramLogCSVFileClass.GetCurrentStaticMethod()));
}
finally
{
if (reader != null)
reader.Close();
}
}
}
}