//將一個對象按XML序列化的方式寫入到一個文件,使用的默認的UTF8編碼格式併發
//o爲要序列化的對象編碼
//path保存文件的路徑xml
public static object _lockObj=new object();對象
public static void XmlSerializeToFile(object o,string path)string
{it
XmlSerializeToFile(o,path,Encoding.UTF8);io
}object
//encoding 編碼方式coding
//path 文件路徑file
public static void XmlSerializeToFile(object o,string path,Encoding encoding)
{
if(string.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
Monitor.Enter(_lockObj);//添加排他鎖,解決併發寫入問題
try
{
using(FileStream file=new FileStream(path,FileMode.Create,FileAccess.Write))
{
XmlSerializeInternal(file,o,encoding);
}
}
catch(Exception)
{
throw;
}
finally
{
Monitor.Exit(_lockObj);
}
}
//讀入一個文件,並按XML的方式反序列化對象
public static T XmlDeserializeFromFile<T>(string path,Encoding encoding)
{
if(string.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if(encoding == null)
throw new ArgumentNullException("encoding");
string xml=File.ReadAllText(path,encoding);
return XmlDeserialize<T>(xml,encoding);
}
pubic static T XmlDeserializeFromFile<T>(string path)
{
return XmlDeserializeFromFile<T>(path,Encoding.UTF8);
}