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
{
///
/// 读取文件
///
///
///
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;
}
}
///
/// 创建并写入文件
///
///
///
///
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;
}
}
///
/// 实体类转XML
///
///
///
///
public static string XmlSerialize(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();
}
}
///
/// XML转实体类
///
///
///
///
public static T DESerializer(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;
}
}
}
}