using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Sys
{
[Serializable] //指示一个类可以序列化
public class Element
{
//复制对象
public object DeepClone()
{
object result = null;
using (MemoryStream ms = new MemoryStream()) //内存流
{
BinaryFormatter bf = new BinaryFormatter();//以二进制格式序列化对象
bf.Serialize(ms, this);//将对象序列化为内存流
ms.Seek(0, SeekOrigin.Begin);
result = bf.Deserialize(ms); //将内存流反序列化为对象
}
return result;
}
//保存对象到文件
//(对象序列化到ms)→(ms写入byte[])→(byte[]写入流)
public void WriteInstanceToFile(string fileName)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[ms.Length];
ms.Read(buffer, 0, buffer.Length);
ms.Seek(0, SeekOrigin.Begin);
FileStream stream = new FileStream(fileName, FileMode.Create);
stream.Write(buffer,0,buffer.Length);
}
}
//从文件中读取对象
public static object ReadInstanceFromFile(string fileName)
{
object result = null;
FileStream stream = new FileStream(fileName, FileMode.Open);//以二进制格式序列化对象
BinaryFormatter bf = new BinaryFormatter();
result = bf.Deserialize((Stream)stream); //流反序列化为对象
stream.Close();
return result;
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Sys
{
[Serializable] //指示一个类可以序列化
public class Element
{
//复制对象
public object DeepClone()
{
object result = null;
using (MemoryStream ms = new MemoryStream()) //内存流
{
BinaryFormatter bf = new BinaryFormatter();//以二进制格式序列化对象
bf.Serialize(ms, this);//将对象序列化为内存流
ms.Seek(0, SeekOrigin.Begin);
result = bf.Deserialize(ms); //将内存流反序列化为对象
}
return result;
}
//保存对象到文件
//(对象序列化到ms)→(ms写入byte[])→(byte[]写入流)
public void WriteInstanceToFile(string fileName)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[ms.Length];
ms.Read(buffer, 0, buffer.Length);
ms.Seek(0, SeekOrigin.Begin);
FileStream stream = new FileStream(fileName, FileMode.Create);
stream.Write(buffer,0,buffer.Length);
}
}
//从文件中读取对象
public static object ReadInstanceFromFile(string fileName)
{
object result = null;
FileStream stream = new FileStream(fileName, FileMode.Open);//以二进制格式序列化对象
BinaryFormatter bf = new BinaryFormatter();
result = bf.Deserialize((Stream)stream); //流反序列化为对象
stream.Close();
return result;
}
}
}