|
@@ -0,0 +1,59 @@
|
|
|
|
+using System;
|
|
|
|
+using System.Collections.Generic;
|
|
|
|
+using System.IO;
|
|
|
|
+using System.Linq;
|
|
|
|
+using System.Text;
|
|
|
|
+using System.Threading.Tasks;
|
|
|
|
+using System.Xml.Serialization;
|
|
|
|
+
|
|
|
|
+namespace MvvmScaffoldFrame48.DLL.ConfigTools
|
|
|
|
+{
|
|
|
|
+ public static class XMLReadWrite
|
|
|
|
+ {
|
|
|
|
+ /// <summary>
|
|
|
|
+ /// 序列化对象到XML文件
|
|
|
|
+ /// </summary>
|
|
|
|
+ /// <typeparam name="T"></typeparam>
|
|
|
|
+ /// <param name="data"></param>
|
|
|
|
+ /// <param name="filePath"></param>
|
|
|
|
+ /// <exception cref="InvalidOperationException"></exception>
|
|
|
|
+ public static void SerializeToXml<T>(T data, string filePath)
|
|
|
|
+ {
|
|
|
|
+ try
|
|
|
|
+ {
|
|
|
|
+ var serializer = new XmlSerializer(typeof(T));
|
|
|
|
+ using (var writer = new StreamWriter(filePath))
|
|
|
|
+ {
|
|
|
|
+ serializer.Serialize(writer, data);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ catch (Exception ex)
|
|
|
|
+ {
|
|
|
|
+ throw new InvalidOperationException("XML serialization failed", ex);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ /// <summary>
|
|
|
|
+ /// 从XML文件反序列化对象
|
|
|
|
+ /// </summary>
|
|
|
|
+ /// <typeparam name="T"></typeparam>
|
|
|
|
+ /// <param name="filePath"></param>
|
|
|
|
+ /// <returns></returns>
|
|
|
|
+ /// <exception cref="InvalidOperationException"></exception>
|
|
|
|
+ public static T DeserializeFromXml<T>(string filePath)
|
|
|
|
+ {
|
|
|
|
+ try
|
|
|
|
+ {
|
|
|
|
+ var serializer = new XmlSerializer(typeof(T));
|
|
|
|
+ using (var reader = new StreamReader(filePath))
|
|
|
|
+ {
|
|
|
|
+ return (T)serializer.Deserialize(reader);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ catch (Exception ex)
|
|
|
|
+ {
|
|
|
|
+ throw new InvalidOperationException("XML deserialization failed", ex);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+}
|