当前位置:网站首页>C# Winform开发 数据的序列化与反序列化
C# Winform开发 数据的序列化与反序列化
2022-07-22 11:07:00 【多层感只鸡】
C#的序列化一共有三种方案,二进制格式(使用BinaryFormatter序列化器)、SOAP格式(使用SoapFormatter序列化器)、XML格式(使用XmlSerializer序列化器)。这里只涉及XML序列化:
因为这里C#中的后台数据都来自于XML文件,因此需要对XML文件进行读写,写入XML文件需要提供需要序列化的参数和路径,而反序列化仅需要提供路径即可。这里注意序列化时不要出现循环引用的情况,不然会序列化失败。
头文件:using System.Xml.Serialization;
序列化代码:
public static void WriteExerciseToXml(AbstractExercise exercise, string fileName)
{
if (exercise == null
|| fileName == null)
{
throw new System.ArgumentNullException();
}
// open the XML file in FileStream
// overwrite the file if it exists, otherwise create a new one
FileStream xmlFile = new FileStream(fileName, FileMode.Create);
// create a text XML writer
// associated it with the opened XML file stream above
XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateTextWriter(xmlFile);
// create a serializer for the AbstractExercise type
DataContractSerializer serializer =
new DataContractSerializer(typeof(AbstractExercise));
// serialize the exercise object
serializer.WriteObject(xmlWriter, exercise);
// close streams
xmlWriter.Close();
xmlFile.Close();
}
反序列化代码:
// deserialize an object from the given XML file
public static AbstractExercise ReadExerciseFromXml(string fileName)
{
if (fileName == null)
{
throw new System.ArgumentNullException();
}
// open XML file in FileStream
FileStream xmlFile = new FileStream(fileName, FileMode.Open);
// crete a text XML reader
// associated it with the opened XML file above
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(xmlFile, new XmlDictionaryReaderQuotas());
// create a serializer for the AbstratExercise type
DataContractSerializer serizalizer = new DataContractSerializer(typeof(AbstractExercise));
// Deserialize the object
AbstractExercise exercise = (AbstractExercise)serizalizer.ReadObject(reader, true);
// close streams
reader.Close();
xmlFile.Close();
return exercise;
}
边栏推荐
猜你喜欢
Juc-6.2-concurrency container copyonwritearraylist
Pytoch automatic derivation
云报传媒广场数字电视转模拟系统设计分享
acwing-飞行员兄弟
Buuctf entry diary -- [suctf 2019]checkin1()
10.系统信息相关命令
Buuctf breakthrough diary 04 -- [actf2020 freshman competition]include1
喝汽水情景 2: 递归
Wechat applet comprehensive case practice 1
Learning notes of wechat applet introduction tutorial - operation feedback of UI chapter
随机推荐
四六级英语听力发射无线广播系统在广东海洋大学阳江校区的应用
NVIDIA CLARA资料
Buuctf breakthrough diary 03 -- [geek challenge 2019] havefun1
隧道调频广播覆盖系统数字选频光纤拉远漏缆覆盖解决方案
操场运动场室外扩声系统方案与功能分析
小区IP网络广播背景系统解决方案-基于局域网、专网或广域网传输
[lttng learning journey] - simply add a trace point to the user program
sed使用心得
8. Memory and disk management
链表中的双指针——快慢指针
source insight打开时闪退的解决办法
英语四六级听力有线传输无线发射系统方案
Wechat applet introduction tutorial learning notes
喝汽水情景 2: 递归
Chapter 8: custom exception return
Human stars website collection plan -- Michael kerrisk
[lttng learning journey] - trace control -- advanced
6. Manage servers and services
Buuctf breakthrough diary 02-- [hctf 2018] warmup1
1.1.2计网——标准化工作机器相关组织,性能指标