Files
hsuco_cctv_getdata/HSUCO_CCTV_GetData/XmlSystem.cs
2023-03-14 17:36:34 +09:00

82 lines
2.5 KiB
C#

using System;
using System.IO;
using System.Xml.Serialization;
public static class XmlSystem
{
public static bool Save<T>(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<T>(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)
{
return default;
}
}
}
public static T LoadFromData<T>(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)
{
return default;
}
}
}
}