添加项目文件。
This commit is contained in:
74
SamplePre.Common/Helper/XmlSerializerHelper.cs
Normal file
74
SamplePre.Common/Helper/XmlSerializerHelper.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace SamplePre.Common.Helper
|
||||
{
|
||||
/// <summary>
|
||||
/// XML序列化/反序列化工具类(强类型读取)
|
||||
/// </summary>
|
||||
public static class XmlSerializerHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 从XML文件反序列化为指定类型的对象
|
||||
/// </summary>
|
||||
/// <typeparam name="T">目标实体类型</typeparam>
|
||||
/// <param name="filePath">XML文件路径</param>
|
||||
/// <returns>实体对象</returns>
|
||||
public static T DeserializeFromXml<T>(string filePath) where T : class, new()
|
||||
{
|
||||
// 检查文件是否存在
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
throw new FileNotFoundException("XML配置文件不存在", filePath);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// 初始化序列化器
|
||||
XmlSerializer serializer = new XmlSerializer(typeof(T));
|
||||
// 读取文件并反序列化
|
||||
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
return serializer.Deserialize(fs) as T;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("XML反序列化失败,检查XML格式和实体类是否匹配", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将对象序列化为XML并保存到文件
|
||||
/// </summary>
|
||||
/// <typeparam name="T">实体类型</typeparam>
|
||||
/// <param name="obj">实体对象</param>
|
||||
/// <param name="filePath">保存路径</param>
|
||||
public static void SerializeToXml<T>(T obj, string filePath) where T : class
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(obj), "序列化对象不能为null");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
XmlSerializer serializer = new XmlSerializer(typeof(T));
|
||||
// 写入文件(UTF8编码,避免中文乱码)
|
||||
using (StreamWriter sw = new StreamWriter(filePath, false, System.Text.Encoding.UTF8))
|
||||
{
|
||||
serializer.Serialize(sw, obj);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("XML序列化失败", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user