(转)序列化与反序列化的初步学习

本文详细介绍了使用C#进行序列化和反序列化的具体实现,包括二进制序列化、XML序列化的方法及其实例代码,展示了如何将对象状态保存到文件中并从文件中恢复。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码
//写入文件
FileStream fs =new FileStream(@"E:\TK.txt", FileMode.Create);
StreamWriter sw
=new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.Write(
this.TextBox1.Text);
sw.Close();
sw.Dispose();
fs.Close();
//读取文件
using (FileStream fs =new FileStream(@"F:\Tddd.txt", FileMode.Open))
{
StreamReader sr
=new StreamReader(fs, System.Text.Encoding.UTF8);
this.TextBox2.Text = sr.ReadToEnd();
sr.Close();
sr.Dispose();
}

 

1 using System;
2  using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7 using System.Runtime.Serialization.Formatters.Binary;
8 using System.Xml.Serialization;
9
10
11 using System.IO;
12
13 publicpartialclass _Default : System.Web.UI.Page
14 {
15 privatestring strFile =@"F:\Book.data";
16 privatestring xmlFile =@"F:\Book.xml";
17 // private string soapFile = @"F:\Book.soap";
18 protectedvoid Page_Load(object sender, EventArgs e)
19 {
20
21 Book book =new Book();
22 book.ID =1;
23 book.BookName ="C#序列化学习";
24 book.BookPrice =52.66;
25 SerializeEntity(book);
26 Book b = DeSerializeEntity();
27 Response.Write("实体:"+ b.BookPrice);
28
29
30 SerializeableXML(book);
31
32 Book bookXml = DeserializeableXML();
33 Response.Write("XML:"+book.BookName);
34 }
35
36 ///<summary>
37 /// 序列化实体
38 ///</summary>
39 ///<param name="book"></param>
40 publicvoid SerializeEntity(Book book)
41 {
42 using (FileStream fs =new FileStream(strFile, FileMode.Create))
43 {
44 BinaryFormatter bf =new BinaryFormatter();
45 bf.Serialize(fs, book);
46 }
47 }
48
49
50 ///<summary>
51 /// 反序列化实体
52 ///</summary>
53 ///<returns></returns>
54 public Book DeSerializeEntity()
55 {
56 Book book;
57 using (FileStream fs =new FileStream(strFile, FileMode.Open))
58 {
59 BinaryFormatter bf =new BinaryFormatter();
60 book = (Book)bf.Deserialize(fs);
61 }
62 return book;
63 }
64
65 ///<summary>
66 /// 序列化XML
67 ///</summary>
68 ///<param name="book"></param>
69 publicvoid SerializeableXML(Book book)
70 {
71 using (FileStream fs =new FileStream(xmlFile, FileMode.Create))
72 {
73 XmlSerializer xs =new XmlSerializer(typeof(Book));
74 xs.Serialize(fs, book);
75 }
76 }
77
78 ///<summary>
79 /// 反序列化XML
80 ///</summary>
81 ///<returns></returns>
82 public Book DeserializeableXML()
83 {
84 Book book =new Book();
85 using (FileStream fs =new FileStream(xmlFile, FileMode.Open))
86 {
87 XmlSerializer xs =new XmlSerializer(typeof(Book));
88 book = (Book)xs.Deserialize(fs);
89 }
90 return book;
91 }
92
93 }
94

 

转载于:https://www.cnblogs.com/konglingxing/archive/2010/11/27/1890021.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值