html5中文学习网

您的位置: 首页 > 网络编程 > ASP.NET » 正文

C#对象序列化和反序列化_.NET教程_编程技术

[ ] 已经帮助:人解决问题

C#对象序列化和反序列化,如下代码示例:Rq7HTML5中文学习网 - HTML5先行者学习网

  1. using System; 
  2. using System.Text; 
  3. using System.Collections.Generic; 
  4. using System.IO; 
  5. using System.Runtime.Serialization.Formatters.Binary; 
  6.  
  7. class SerializableOperate 
  8.     private static void ObjectSerializable(object obj, string filePath) 
  9.     { 
  10.         FileStream fs = null
  11.         try 
  12.         { 
  13.             fs = new FileStream(filePath, FileMode.Create); 
  14.             BinaryFormatter bf = new BinaryFormatter(); 
  15.             bf.Serialize(fs, obj); 
  16.         } 
  17.         catch (IOException ex) 
  18.         { 
  19.             Console.WriteLine("序列化是出错!"); 
  20.         } 
  21.         finally 
  22.         { 
  23.             if (fs != null
  24.             { 
  25.                 fs.Close(); 
  26.             } 
  27.         } 
  28.     } 
  29.     private static object ObjectUnSerializable(string filePath) 
  30.     { 
  31.         FileStream fs = null
  32.         object obj = null
  33.         try 
  34.         { 
  35.             fs = new FileStream(filePath, FileMode.OpenOrCreate); 
  36.             BinaryFormatter bf = new BinaryFormatter(); 
  37.             obj = bf.Deserialize(fs); 
  38.         } 
  39.         catch (IOException ex) 
  40.         { 
  41.             Console.WriteLine("反序列化时出错!"); 
  42.         } 
  43.         finally 
  44.         { 
  45.             if (fs != null
  46.             { 
  47.                 fs.Close(); 
  48.             } 
  49.         } 
  50.         return obj; 
  51.     } 
  52.  
  53.     static void Main(String[] args) 
  54.     { 
  55.         List<string> list = new List<string>{ 
  56.         "张三","李四","王五","赵柳","刘备" 
  57.        }; 
  58.         string filePath = "c://log.log"
  59.         Console.WriteLine("开始序列化集合!请稍等..."); 
  60.         SerializableOperate.ObjectSerializable(list, filePath); 
  61.         Console.WriteLine("开始反序列化集合!请稍等..."); 
  62.         list = (List<String>)SerializableOperate.ObjectUnSerializable(filePath); 
  63.         foreach (string str in list) 
  64.         { 
  65.             Console.WriteLine(str); 
  66.         } 
  67.     } 
Rq7HTML5中文学习网 - HTML5先行者学习网
Rq7HTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助