本文介绍C#对象序列化后保存到文件,然后再从文件中读取数据反序列化成对象。
我这里用lab做例子简单介绍该用法。
下面是自定义的一个可被序列化的lab:
[Serializable]
public class mylabel : System.Windows.Forms.Label, ISerializable
{
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
//获取所有公有属性
System.Reflection.PropertyInfo[] p = GetType().GetProperties();
//遍历该属性
foreach (var v in p)
{
//属性不可读不保存
if (!v.CanRead)
{
continue;
}
//获取属性值
object o = v.GetValue(this, null);
if (o == null)
{
continue;
}
//属性可以被序列化
var att = v.PropertyType.GetCustomAttributes(typeof(SerializableAttribute), true);
if (att == null || att.Length <= 0)
{
continue;
}
info.AddValue(v.Name, o);
}
}
public mylabel() { }
public mylabel(SerializationInfo info, StreamingContext context)
{
System.Reflection.PropertyInfo[] p = GetType().GetProperties();
foreach (var v1 in info)
{
foreach (var v in p)
{
if (v1.Name != v.Name || !v.CanWrite)
{
continue;
}
var att = v.PropertyType.GetCustomAttributes(typeof(SerializableAttribute), true);
if (att == null || att.Length <= 0)
{
continue;
}
object o = info.GetValue(v.Name, v.PropertyType);
string s = v.PropertyType.ToString();
if (v.Name == "AutoScroll" && v.DeclaringType.ToString() == "System.Windows.Forms.ToolStrip")
{
continue;
}
v.SetValue(this, o);
}
}
}
}
我在Form中引用该控件:
public partial class Form1 : Form
{
private string path = @".\mylabel.data";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.mylabel1.Text = "保存按下";
using (FileStream fStream = new FileStream( path, FileMode.OpenOrCreate, FileAccess.Write))
{
BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
binFormat.Serialize(fStream, this.mylabel1);
}
this.Controls.Remove(this.mylabel1);
}
private void button2_Click(object sender, EventArgs e)
{
if (!File.Exists(path))
{
return;
}
using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
Random r = new Random();
int x = r.Next(0, this.Width);
int y = r.Next(0, this.Height);
BinaryFormatter b = new BinaryFormatter();
Label lab = b.Deserialize(fileStream) as Label;
if (lab != null)
{
lab.Location = new Point(x, y);
this.Controls.Add(lab);
}
}
}
}
最后可以看到lab被保存在mylabel.data文件中,并重新读取后放到一个随机的位置。