using System;
using System.Runtime.Serialization;
namespace ConsoleApp_SerializableToAnotherObj
{
class Program
{
static void Main(string[] args)
{
//反序列化为另一个对象
Person personA=new Person(){FirstName = "Zhang",LastName = "San"};
BinarySerializer.SerializeToFile(personA,@"c:\","person.txt");
PersonAnother p = BinarySerializer.DeserializeFromFile<PersonAnother>(@"c:\person.txt");
Console.WriteLine(p.Name);
Console.ReadKey();
}
}
[Serializable]
class PersonAnother : ISerializable
{
public string Name { get; set; }
protected PersonAnother(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("Name");
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
}
}
[Serializable]
class Person : ISerializable
{
public string FirstName;
public string LastName;
public string ChineseName;
public Person()
{
}
protected Person(SerializationInfo info, StreamingContext context)
{ }
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(PersonAnother));
info.AddValue("Name", string.Format("{0} {1}", LastName, FirstName));
}
}
}
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApp_SerializableToAnotherObj
{
public class BinarySerializer
{
/// <summary>
/// 将类型序列化为字符串
/// </summary>
public static string Serialize<T>(T t)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
return System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
}
/// <summary>
/// 将类型序列化为文件
/// </summary>
public static void SerializeToFile<T>(T t, string path, string fullname)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fullPath = string.Format(@"{0}\{1}", path, fullname);
using (FileStream stream = new FileStream(fullPath, FileMode.OpenOrCreate))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
stream.Flush();
}
}
/// <summary>
/// 将字符串反序列化为类型
/// </summary>
public static TResult Deserialize<TResult>(string s) where TResult : class
{
byte[] bs = System.Text.Encoding.UTF8.GetBytes(s);
using (MemoryStream stream = new MemoryStream(bs))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
}
/// <summary>
/// 将文件反序列化为类型
/// </summary>
public static TResult DeserializeFromFile<TResult>(string path) where TResult : class
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
}
}
}
原文:http://www.cnblogs.com/jx270/p/3659982.html