C# 序列号和反序列化 对象写入bin

https://www.cnblogs.com/BrightMoon/archive/2013/02/24/2924262.html

复制代码
序列化是将对象在内存中的2进制数据写入到bin文件中,
这个操作就需要引入命名空间
using System.Runtime.Serialization.Formatters.Binary;
以下是序列化和反序列化代码

序列化代码:
    /// <summary> /// 保存配置文件 /// </summary> public void SaveFile() {
首先将数据保存到作临时存储用的泛型中 manager.Temp.Clear();
foreach (TreeNode node in this.tvSongList.Nodes) { List<SongInfo> songList = node.Tag as List<SongInfo>; Temp temp = new Temp(); temp.TreeNodeName = node.Text; temp.SongList = songList; manager.Temp.Add(temp); }
打开文件流,创建BinaryFormatter对象
调用BinaryFormatter对象的Serialize方法,传入两个参数(文件流对象,需要序列化的对象)
因为序列化的时候需要用到文件流,因为使用文件流时可能出现异常,所以用try{}catch{}检测异常
try { FileStream fs = new FileStream(@"save.bin", FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, manager); fs.Close(); } catch (Exception) { return; } }
反序列化代码:
创建文件流,创建BinaryFormatter对象
调用BinaryFormatter对象的Deserialize方法,传入参数(文件流对象)
将需要Deserialize的返回值强制转换,然后赋值给需要反序列化的对象

因为序列化的时候需要用到文件流,因为使用文件流时可能出现异常,所以用try{}catch{}检测异常
复制代码
            try
            {
                FileStream fs = new FileStream(@"save.bin", FileMode.Open);
                BinaryFormatter bf = new BinaryFormatter();
                this.manager = (SongManager)bf.Deserialize(fs);
                fs.Close();
            }
            catch (Exception)
            {
                return;
            } 
复制代码


 
复制代码
原文地址:https://www.cnblogs.com/sunny3158/p/14341816.html