市长热线演示版

SerializationHelper.cs 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.IO;
  3. using System.Xml.Serialization;
  4. using System.Web.Script.Serialization;
  5. using System.Data;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. namespace HySoft.Common
  9. {
  10. public static class SerializationHelper
  11. {
  12. /// <summary>
  13. /// 反序列化
  14. /// </summary>
  15. /// <param name="type">对象类型</param>
  16. /// <param name="filename">文件路径</param>
  17. /// <returns></returns>
  18. public static object Load(Type type, string filename)
  19. {
  20. FileStream fs = null;
  21. try
  22. {
  23. // open the stream...
  24. fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  25. XmlSerializer serializer = new XmlSerializer(type);
  26. return serializer.Deserialize(fs);
  27. }
  28. catch (Exception ex)
  29. {
  30. throw ex;
  31. }
  32. finally
  33. {
  34. if (fs != null)
  35. fs.Close();
  36. }
  37. }
  38. /// <summary>
  39. /// 序列化
  40. /// </summary>
  41. /// <param name="obj">对象</param>
  42. /// <param name="filename">文件路径</param>
  43. public static void Save(object obj, string filename)
  44. {
  45. FileStream fs = null;
  46. // serialize it...
  47. try
  48. {
  49. fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
  50. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  51. serializer.Serialize(fs, obj);
  52. }
  53. catch (Exception ex)
  54. {
  55. throw ex;
  56. }
  57. finally
  58. {
  59. if (fs != null)
  60. fs.Close();
  61. }
  62. }
  63. /// <summary>
  64. /// DataTable转Json,[{},{},{}]形式
  65. /// </summary>
  66. /// <param name="dt"></param>
  67. /// <returns></returns>
  68. public static string DataToJson(this DataTable dt)
  69. {
  70. JavaScriptSerializer jss = new JavaScriptSerializer();
  71. ArrayList dic = new ArrayList();
  72. foreach (DataRow dr in dt.Rows)
  73. {
  74. Dictionary<string, object> drow = new Dictionary<string, object>();
  75. foreach (DataColumn dc in dt.Columns)
  76. {
  77. drow.Add(dc.ColumnName, dr[dc.ColumnName]);
  78. }
  79. dic.Add(drow);
  80. }
  81. return jss.Serialize(dic);
  82. }
  83. }
  84. }