C#对象序列化和反序列化 |
作者:管理员 来源:本站 浏览次数:5039 发布时间:2014-12-5 13:32:59 |
C#对象序列化和反序列化,如下代码示例:![]() using System; using System.Text; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; class SerializableOperate { private static void ObjectSerializable(object obj, string filePath) { FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, obj); } catch (IOException ex) { Console.WriteLine("序列化是出错!"); } finally { if (fs != null) { fs.Close(); } } } private static object ObjectUnSerializable(string filePath) { FileStream fs = null; object obj = null; try { fs = new FileStream(filePath, FileMode.OpenOrCreate); BinaryFormatter bf = new BinaryFormatter(); obj = bf.Deserialize(fs); } catch (IOException ex) { Console.WriteLine("反序列化时出错!"); } finally { if (fs != null) { fs.Close(); } } return obj; } static void Main(String[] args) { List "张三","李四","王五","赵柳","刘备" }; string filePath = "c:\\log.log"; Console.WriteLine("开始序列化集合!请稍等..."); SerializableOperate.ObjectSerializable(list, filePath); Console.WriteLine("开始反序列化集合!请稍等..."); list = (List foreach (string str in list) { Console.WriteLine(str); } } } |