1、BinaryFormatter二进制序列化对象实例到文件
View Code
FileStream fs = new FileStream("DataFile.dat", FileMode.Create); // Construct a BinaryFormatter and use it to serialize the data to the stream. BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(fs, obj); } catch (SerializationException e) { throw; } finally { fs.Close(); }
View Code
public static object Deserialize() { FileStream fs = new FileStream("DataFile.dat", FileMode.Open); try { BinaryFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(fs); } catch (SerializationException e) { throw; } finally { fs.Close(); } }
2、BinaryFormatter二级制序列化对象
View Code
IFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, obj); long count = stream.Length; byte[] buff = stream.ToArray(); obj = Convert.ToBase64String(buff); }
View Code
IFormatter fter = new BinaryFormatter(); byte[] buff = Convert.FromBase64String(serializedObject); using (Stream stream = new MemoryStream(buff)) { obj = fter.Deserialize(stream); }
3、BinaryFormatter深拷贝
View Code
public static T CloneOf<T>(T serializableObject) { object objCopy = null; MemoryStream stream = new MemoryStream(); BinaryFormatter binFormatter = new BinaryFormatter(); binFormatter.Serialize(stream, serializableObject); stream.Position = 0; objCopy = (T)binFormatter.Deserialize(stream); stream.Close(); return (T)objCopy; }