第8章 流和序列化

8.1 文件

8.1.1 不同视角下的文件

应用程序级,人类可阅读级,机器级

8.1.2 位,字节和字节数组

8.2 流

8.2.1 关于流的类比

8.2.2 使用流进行文件复制

1.一次性复制

2.循环分批复制

当打开或创建文件时,流指针默认位于文件头,当调用read或write方法后,流指针会自动向后移动相应的字节。因此在代码中无需设置,每次调用read或write时,读取的都是未处理的字节。

8.2.3 流的类型体系

1.基础流

从流中读取数据:canread;read;readbyte

向流中写入数据:canwrite;write;writebyte

移动流指针:canseek;seek;position;close;dispose;flush;

超时处理:cantimeout;readtimeout;writetimeout;

流长度:length;setlength

2.装饰器流

1)包含stream流基类的引用

2)没有后备存储概念

bufferedstream;deflatestream;gzipstream

3.包装器类

1)streamreader和streamwriter

2)binaryreader和binarywriter

4.帮助类

file静态类:open;openwrite;openread;readalltext;readallbytes;writeallbytes;writealllines;copy

fileinfo;path;directory;dicrectoryinfo

8.3 序列化

8.3.1 基本操作

IFormatter:serialize;deserialize

binaryformatter和soapformatter

默认情况下类型都是不可序列化的,需要明确指出[Serializable]特性(133)

序列化不光需要该类型是标记为Serializable,类型中的属性和字段也需要是可序列化的。如不需要序列化,用[NonSerialized]特性标记,该特性只能加在字段上,不能加在属性上(134)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Product product = new Product(188) { Price = 4998.5F, Name = "Lumia 920" };
            IFormatter formatter = new BinaryFormatter();
            Stream fs = File.OpenWrite(@"C:UsersAdministratorDesktopproduct.obj");
            formatter.Serialize(fs, product);
            fs.Dispose();
            Console.WriteLine(product);
            //IFormatter formatter = new BinaryFormatter();
            //Stream fs = File.OpenRead(@"C:UsersAdministratorDesktopproduct.obj");
            //Product product = (Product)formatter.Deserialize(fs);
            //fs.Dispose();
            //Console.WriteLine(product);
            Console.Read();
        }

        [Serializable]
        public class Product:IDeserializationCallback
        {
            private int id;
            public string Name { get; set; }
            public double Price { get; set; }
            [NonSerialized]
            private SqlConnection conn;
            public Product(int id)
            {
                this.id = id;
                conn = new SqlConnection(@"Data Source=.;Initial Catalog=DB;User ID=sa;Password=123");
            }
            public override string ToString()
            {
                return string.Format("id:{0},name:{1},price:{2},conn:{3}", this.id, this.Name, this.Price, this.conn == null ? "NULL" : "OBJECT");
            }

            public void OnDeserialization(object sender)
            {
                conn = new SqlConnection(@"Data Source=.;Initial Catalog=DB;User ID=sa;Password=123");
            }
        }
    }
}
View Code

 将对象序列化为字节数组:

MemoryStream stream = new MemoryStream();
IFormatter f = new BinaryFormatter();
f.Serialize(stream, infos);
byte[] buffer = stream.GetBuffer();

 反序列化:

MemoryStream stream = new MemoryStream(receiveBuffer, 0, r);
infos device = (infos)formatter.Deserialize(stream);

8.3.2 事件响应

[OnSerializing]

[OnSerialized]

[OnDeserializing]

[OnDeserialized]

四个特性对应四个事件方法

8.3.3 自定义序列化过程

原文地址:https://www.cnblogs.com/liuslayer/p/5404245.html