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

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

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Xml;using System.Xml.Serialization;namespace Utility{    public class Serialization    {        // 序列化        public static void EnS(string fileName = @"D:\test.xml", object obj = null)        {            fileName = Guid.NewGuid().ToString() + ".xml";            obj = Guid.NewGuid();            using (Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))            {                using (XmlWriter writer = XmlWriter.Create(stream))                {                    try                    {                        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();                        ns.Add(string.Empty, string.Empty);                        XmlSerializer xmls = new XmlSerializer(obj.GetType());                        xmls.Serialize(writer, obj, ns);                    }                    catch (Exception exp)                    {                        string message = string.Format("保存{0}时发生错误", obj.GetType().Name);                        throw new Exception(message);                    }                }            }        }        // 反序列化        public static T Load
(string fileName = @"D:\test.xml") { using (Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { using (XmlReader reader = XmlReader.Create(stream)) { try { XmlSerializer xmls = new XmlSerializer(typeof(T)); return (T)xmls.Deserialize(reader); } catch (Exception exp) { string message = string.Format("装载{0}时发生错误", typeof(T).Name); throw new Exception(message, exp); } } } } }}

 

转载于:https://www.cnblogs.com/mtsl/p/4232464.html

你可能感兴趣的文章
Hive语法手册
查看>>
tomcat和jboss下的debug模式设置
查看>>
Python爬虫(十一)_案例:使用正则表达式的爬虫
查看>>
JavaWeb学习笔记--3.JavaBean
查看>>
[hardware][intel] intel全系列网卡调研
查看>>
考试总结2017.7.29
查看>>
async/await小知识点
查看>>
通过控制台运行程序
查看>>
Pycharm中配置Git版本管理
查看>>
手机app测试之我见
查看>>
Fiddler实现移动端手机抓包
查看>>
wps直接打开CVS文件会把长串数字订单号最后4位变为0
查看>>
BPM配置故事之案例8-根据表单数据调整审批线路
查看>>
LeetCode OJ 3Sum 3个整数之和
查看>>
Knockout应用开发指南 第八章:简单应用举例(2)
查看>>
Bootstrap WPF Style,Bootstrap风格的WPF样式
查看>>
Stern-Brocot Tree [HDU 4556]
查看>>
103 Binary Tree Zigzag Level Order Traversal 二叉树的锯齿形层次遍历
查看>>
springboot项目中使用maven resources
查看>>
ubuntu12.04 卸载和安装mysql
查看>>