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> list = new List<string>{
- "张三","李四","王五","赵柳","刘备"
- };
- string filePath = "c:\\log.log";
- Console.WriteLine("开始序列化集合!请稍等...");
- SerializableOperate.ObjectSerializable(list, filePath);
- Console.WriteLine("开始反序列化集合!请稍等...");
- list = (List<String>)SerializableOperate.ObjectUnSerializable(filePath);
- foreach (string str in list)
- {
- Console.WriteLine(str);
- }
- }
- }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索using
, system
, filestream
, filepath
, console
, WriteLine
C#序列化
c站、c语言、cf、ch、c罗,以便于您获取更多的相关知识。
时间: 2024-12-09 01:44:23