博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 序列化
阅读量:5084 次
发布时间:2019-06-13

本文共 5307 字,大约阅读时间需要 17 分钟。

 

序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,可以轻松地存储和传输数据。
using System;using System.IO;using System.Text;using System.Xml;using System.Xml.Serialization;//using System.Runtime.Serialization.Json;using System.Runtime.Serialization.Formatters.Soap;using System.Runtime.Serialization.Formatters.Binary;namespace DotNet.Utilities{    public class SerializeHelper    {        public SerializeHelper()        { }        #region XML序列化        ///         /// 文件化XML序列化        ///         /// 对象        /// 文件路径        public static void Save(object obj, string filename)        {            FileStream fs = null;            try            {                fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);                XmlSerializer serializer = new XmlSerializer(obj.GetType());                serializer.Serialize(fs, obj);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (fs != null) fs.Close();            }        }        ///         /// 文件化XML反序列化        ///         /// 对象类型        /// 文件路径        public static object Load(Type type, string filename)        {            FileStream fs = null;            try            {                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);                XmlSerializer serializer = new XmlSerializer(type);                return serializer.Deserialize(fs);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (fs != null) fs.Close();            }        }        ///         /// 文本化XML序列化        ///         /// 对象        public string ToXml
(T item) { XmlSerializer serializer = new XmlSerializer(item.GetType()); StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb)) { serializer.Serialize(writer, item); return sb.ToString(); } } ///
/// 文本化XML反序列化 /// ///
字符串序列 public T FromXml
(string str) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (XmlReader reader = new XmlTextReader(new StringReader(str))) { return (T)serializer.Deserialize(reader); } } #endregion #region Json序列化 ///
/// JsonSerializer序列化 /// ///
对象 //public string ToJson
(T item) //{ // DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType()); // using (MemoryStream ms = new MemoryStream()) // { // serializer.WriteObject(ms, item); // return Encoding.UTF8.GetString(ms.ToArray()); // } //} /////
///// JsonSerializer反序列化 ///// /////
字符串序列 //public T FromJson
(string str) where T : class //{ // DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); // using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str))) // { // return serializer.ReadObject(ms) as T; // } //} #endregion #region SoapFormatter序列化 ///
/// SoapFormatter序列化 /// ///
对象 public string ToSoap
(T item) { SoapFormatter formatter = new SoapFormatter(); using (MemoryStream ms = new MemoryStream()) { formatter.Serialize(ms, item); ms.Position = 0; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(ms); return xmlDoc.InnerXml; } } ///
/// SoapFormatter反序列化 /// ///
字符串序列 public T FromSoap
(string str) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(str); SoapFormatter formatter = new SoapFormatter(); using (MemoryStream ms = new MemoryStream()) { xmlDoc.Save(ms); ms.Position = 0; return (T)formatter.Deserialize(ms); } } #endregion #region BinaryFormatter序列化 ///
/// BinaryFormatter序列化 /// ///
对象 public string ToBinary
(T item) { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { formatter.Serialize(ms, item); ms.Position = 0; byte[] bytes = ms.ToArray(); StringBuilder sb = new StringBuilder(); foreach (byte bt in bytes) { sb.Append(string.Format("{0:X2}", bt)); } return sb.ToString(); } } ///
/// BinaryFormatter反序列化 /// ///
字符串序列 public T FromBinary
(string str) { int intLen = str.Length / 2; byte[] bytes = new byte[intLen]; for (int i = 0; i < intLen; i++) { int ibyte = Convert.ToInt32(str.Substring(i * 2, 2), 16); bytes[i] = (byte)ibyte; } BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream(bytes)) { return (T)formatter.Deserialize(ms); } } #endregion }}
SerializeHelper

 

转载于:https://www.cnblogs.com/Liyuting/p/7085278.html

你可能感兴趣的文章
JVM参数调优:Eclipse启动实践
查看>>
(旧笔记搬家)struts.xml中单独页面跳转的配置
查看>>
不定期周末福利:数据结构与算法学习书单
查看>>
strlen函数
查看>>
python的列表与shell的数组
查看>>
关于TFS2010使用常见问题
查看>>
软件工程团队作业3
查看>>
python标准库——queue模块 的queue类(单向队列)
查看>>
火狐、谷歌、IE关于document.body.scrollTop和document.documentElement.scrollTop 以及值为0的问题...
查看>>
深入理解JVM读书笔记--字节码执行引擎
查看>>
vue-搜索功能-实时监听搜索框的输入,N毫秒请求一次数据
查看>>
批处理 windows 服务的安装与卸载
查看>>
React文档翻译 (快速入门)
查看>>
nodejs fs路径
查看>>
动态规划算法之最大子段和
查看>>
linux c:关联变量的双for循环
查看>>
深入浅出理解zend framework(三)
查看>>
python语句----->if语句,while语句,for循环
查看>>
javascript之数组操作
查看>>
LinkedList源码分析
查看>>