XmlUntis.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Xml.Serialization;
  8. namespace CommonUtils.xml
  9. {
  10. public class SaveXml
  11. {
  12. #region 保存xml
  13. /// <summary>
  14. /// <para>将类保存成XML或者从XML读取到类</para>
  15. ///
  16. /// </summary>
  17. /// <typeparam name="T"></typeparam>
  18. /// <param name="strFile"></param>
  19. /// <param name="bSave">是否写</param>
  20. /// <param name="obj"></param>
  21. /// <returns></returns>
  22. public static T Serialize<T>(string strFile, bool bSave, ref T obj)
  23. where T : class
  24. {
  25. try
  26. {
  27. XmlSerializer xs = new XmlSerializer(typeof(T));
  28. if ( bSave )
  29. {
  30. string[] temps = strFile.Split('\\');
  31. string temp = "";
  32. for ( int i = 0; i < temps.Length - 1; i++ )
  33. {
  34. temp += temps[ i ];
  35. temp += @"\";
  36. }
  37. Directory.CreateDirectory(temp);
  38. Stream stream = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.Read);
  39. xs.Serialize(stream, obj);
  40. stream.Close();
  41. }
  42. else
  43. {
  44. bool bExist = File.Exists(strFile);
  45. if ( bExist )
  46. {
  47. Stream stream = new FileStream(strFile, FileMode.Open, FileAccess.Read, FileShare.Read);
  48. obj = xs.Deserialize(stream) as T;
  49. stream.Close();
  50. }
  51. else
  52. {
  53. throw new Exception("指定文件不存在");
  54. }
  55. }
  56. }
  57. catch ( System.Exception ex )
  58. {
  59. throw ex;
  60. }
  61. return obj;
  62. }
  63. #endregion
  64. }
  65. }