C#序列化与反序列化代码记录

private static HomePageVO _HomePageVO;
//反序列化
public HomePageVO GetHomePageVO()
{
if (_HomePageVO == null)
{
string strFile = System.Web.HttpContext.Current.Server.MapPath("~/___DB/HomePageVO.xml");
HomePageVO vo;
if (System.IO.File.Exists(strFile))
{
using (FileStream fs = new FileStream(strFile, FileMode.Open))
{
//BinaryFormatter formatter = new BinaryFormatter();
//vo = (HomePageVO)formatter.Deserialize(fs);
XmlSerializer s = new XmlSerializer(typeof(HomePageVO));
vo
= (HomePageVO)s.Deserialize(fs);
_HomePageVO
= vo;
return vo;
}
}
else
{
return new HomePageVO();
}
}
else
{
return _HomePageVO;
}
}

//序列化
public bool SaveHomePageVO(HomePageVO vo)
{
string strFile = System.Web.HttpContext.Current.Server.MapPath("~/___DB/HomePageVO.xml");
using (FileStream fs = new FileStream(strFile, FileMode.Create))
{
//BinaryFormatter formatter = new BinaryFormatter();
//formatter.Serialize(fs, vo);
XmlSerializer s = new XmlSerializer(typeof(HomePageVO));
s.Serialize(fs, vo);
}
_HomePageVO
= vo;
return true;
}
原文地址:https://www.cnblogs.com/ahjesus/p/2040929.html