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

代码
//写入文件
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

 

posted @ 2010-11-27 23:46  Kong, Star  阅读(197)  评论(0编辑  收藏  举报