using System; using System.IO; using System.Xml.Serialization; namespace CommonLibrary { public static class XmlSystem { public static bool Save(string path, T data) where T : struct { if (string.IsNullOrWhiteSpace(path)) { return false; } string directory = Path.GetDirectoryName(System.IO.Path.GetFullPath(path)); if (!System.IO.Directory.Exists(directory)) { Directory.CreateDirectory(directory); } using (StreamWriter sw = new StreamWriter(path)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces(); xmlSerializerNamespaces.Add("", ""); xmlSerializer.Serialize(sw, data, xmlSerializerNamespaces); sw.Close(); } return true; } public static T LoadFromPath(string path) where T : struct { if (string.IsNullOrWhiteSpace(path)) { return default; } string directory = Path.GetDirectoryName(System.IO.Path.GetFullPath(path)); if (!System.IO.Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (!File.Exists(path)) { return default; } using (StreamReader sr = new StreamReader(path)) { try { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); T data = (T)xmlSerializer.Deserialize(sr); return data; } catch (Exception ex) { CommonLibrary.Log.ERROR(ex.Message); return default; } } } public static T LoadFromData(string data) where T : struct { if (string.IsNullOrWhiteSpace(data)) { return default; } using (StringReader sr = new StringReader(data)) { try { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); return (T)xmlSerializer.Deserialize(sr); } catch (Exception ex) { CommonLibrary.Log.ERROR(ex.Message); return default; } } } } }