using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace CommonUtils.xml { public class SaveXml { #region 保存xml /// /// 将类保存成XML或者从XML读取到类 /// /// /// /// /// 是否写 /// /// public static T Serialize(string strFile, bool bSave, ref T obj) where T : class { try { XmlSerializer xs = new XmlSerializer(typeof(T)); if ( bSave ) { string[] temps = strFile.Split('\\'); string temp = ""; for ( int i = 0; i < temps.Length - 1; i++ ) { temp += temps[ i ]; temp += @"\"; } Directory.CreateDirectory(temp); Stream stream = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.Read); xs.Serialize(stream, obj); stream.Close(); } else { bool bExist = File.Exists(strFile); if ( bExist ) { Stream stream = new FileStream(strFile, FileMode.Open, FileAccess.Read, FileShare.Read); obj = xs.Deserialize(stream) as T; stream.Close(); } else { throw new Exception("指定文件不存在"); } } } catch ( System.Exception ex ) { throw ex; } return obj; } #endregion } }