using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApplication2008
{
class Interface_Test{
/// <summary>
/// 将序列化后的信息转换为字符串
/// </summary>
/// <param name="date">要序列化的对象</param>
/// <param name="path">文件路径</param>
static void Serialize(object date, string path)
{
if(File.Exists(path))
File.Delete(path);
using(FileStream fs=new FileStream(path, FileMode.Create, FileAccess.Write)){
BinaryFormatter format = new BinaryFormatter();
format.Serialize(fs, date);
}
}
/// <summary>
/// 反序列化数据
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>object对象</returns>
static object Deserialize(string path)
{
if(!File.Exists(path))
return null;
using(FileStream fs=new FileStream(path, FileMode.Open, FileAccess.Read)){
BinaryFormatter format = new BinaryFormatter();
return format.Deserialize(fs);
}
}
static void Main()
{
People P = new People();
Serialize(P, @"E://test.txt");
object obj = Deserialize(@"E://test.txt");
People P2 = obj as People;
if (obj != null)
{
Console.WriteLine(P2.Name);
}
}
}
[Serializable]
public class People
{
public string Name="广东小子";
public string Sex;
private int _Age=23;
public int Age
{
get { return _Age; }
set { _Age = value; }
}
}
}