public static bool SaveToXML(string strPathXML, object sourceObj, Type type)
{
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(strPathXML)))//判断是否存在,不存在就创建
{
try
{
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(strPathXML));
}
catch
{
return false;
}
}
try
{
XmlSerializer serializer = new XmlSerializer(type);
using (FileStream stream = new FileStream(strPathXML, FileMode.Create))
{
serializer.Serialize(stream, sourceObj);//序列化
stream.Close();
return true;
}
}
catch (Exception ex)
{
return false;
}
}
public static bool LoadFromXML(string strPathXML, Type type, out object data)
{
if (!System.IO.File.Exists(strPathXML))
{
//System.Windows.Forms.MessageBox.Show(strPathXML + " 文件不存在!!");
data = new object();
return false;
}
data= null;
XmlSerializer serializer = new XmlSerializer(type);
using (FileStream stream = new FileStream(strPathXML, FileMode.Open, FileAccess.Read))
{
try
{
data = serializer.Deserialize(stream);//反序列化,返回object外面要强制转换
stream.Close();
}
catch
{
data = new object()
return false;
}
}
return true;
}
C# XML文件操作
最新推荐文章于 2024-06-14 10:41:45 发布