1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- 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);
- }
- }
- }
- }
|