ToolSerialization.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.Xml.Serialization;
  8. using System.Reflection;
  9. using System.Runtime.InteropServices;
  10. namespace Ips.Library.DxpLib
  11. {
  12. public static class ToolSerialization
  13. {
  14. //public static void ToBinaryFile(string fileName, object obj)
  15. //{
  16. // FileStream stream = File.Create(fileName);
  17. // BinaryFormatter binFmt = new BinaryFormatter();
  18. // binFmt.Serialize(stream, obj);
  19. // stream.Close();
  20. //}
  21. //public static object FromBinaryFile(string fileName, Type type)
  22. //{
  23. // FileStream stream = File.OpenRead(fileName);
  24. // BinaryFormatter binFmt = new BinaryFormatter();
  25. // object obj = binFmt.Deserialize(stream);
  26. // stream.Close();
  27. // return obj;
  28. //}
  29. public static void ToXmlFile(string fileName, object obj)
  30. {
  31. StreamWriter writer = null;
  32. try
  33. {
  34. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  35. writer = new StreamWriter(fileName, false, Encoding.UTF8);
  36. serializer.Serialize(writer, obj);
  37. writer.Close();
  38. }
  39. catch
  40. {
  41. if (writer != null)
  42. writer.Close();
  43. throw;
  44. }
  45. }
  46. public static string ToXmlString(object obj)
  47. {
  48. var xmlSerializer = new XmlSerializer(obj.GetType());
  49. using (var stringWriter = new StringWriter())
  50. {
  51. xmlSerializer.Serialize(stringWriter, obj);
  52. using (var streamReader = new StringReader(stringWriter.GetStringBuilder().ToString()))
  53. {
  54. return streamReader.ReadToEnd();
  55. }
  56. }
  57. }
  58. public static object FromXmlFile(string fileName, Type type)
  59. {
  60. StreamReader reader = null;
  61. try
  62. {
  63. XmlSerializer serializer = new XmlSerializer(type);
  64. reader = new StreamReader(fileName);
  65. object obj = serializer.Deserialize(reader);
  66. reader.Close();
  67. return obj;
  68. }
  69. catch
  70. {
  71. if (reader != null)
  72. reader.Close();
  73. throw;
  74. }
  75. }
  76. public static object FromXmlString(string xmlString, Type type)
  77. {
  78. var x = new XmlSerializer(type);
  79. var r = new StringReader(xmlString);
  80. return x.Deserialize(r);
  81. }
  82. public static T FromXmlString<T>(string xmlString)
  83. {
  84. var x = new XmlSerializer(typeof(T));
  85. var r = new StringReader(xmlString);
  86. return (T)x.Deserialize(r);
  87. }
  88. }
  89. }