using System;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Linq;
|
using System.Text;
|
using System.Xml.Serialization;
|
|
namespace TProduct.Common
|
{
|
public class XmlFileHelper
|
{
|
/// <summary>
|
/// 读取文件
|
/// </summary>
|
/// <param name="filePath"></param>
|
/// <returns></returns>
|
public static string ReadFile(string filePath)
|
{
|
try
|
{
|
using (var stream = new FileStream(filePath, FileMode.Open))
|
using (var reader = new StreamReader(stream))
|
{
|
return reader.ReadToEnd();
|
}
|
}
|
catch
|
{
|
return null;
|
}
|
}
|
|
/// <summary>
|
/// 创建并写入文件
|
/// </summary>
|
/// <param name="obj"></param>
|
/// <param name="filePath"></param>
|
/// <returns></returns>
|
public static bool WriteFile(string obj, string fileName)
|
{
|
try
|
{
|
using (var stream = new FileStream(fileName, FileMode.OpenOrCreate))
|
using (var writer = new StreamWriter(stream))
|
{
|
writer.Write(obj);
|
}
|
return true;
|
}
|
catch
|
{
|
return false;
|
}
|
}
|
|
/// <summary>
|
/// 实体类转XML
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="obj"></param>
|
/// <returns></returns>
|
public static string XmlSerialize<T>(T obj)
|
{
|
using (System.IO.StringWriter sw = new StringWriter())
|
{
|
Type t = obj.GetType();
|
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
|
serializer.Serialize(sw, obj);
|
sw.Close();
|
return sw.ToString();
|
}
|
}
|
|
/// <summary>
|
/// XML转实体类
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="strXML"></param>
|
/// <returns></returns>
|
public static T DESerializer<T>(string strXML) where T : class
|
{
|
try
|
{
|
using (StringReader sr = new StringReader(strXML))
|
{
|
XmlSerializer serializer = new XmlSerializer(typeof(T));
|
return serializer.Deserialize(sr) as T;
|
}
|
}
|
catch (Exception ex)
|
{
|
throw ex;
|
}
|
}
|
|
|
}
|
}
|