串行化类,这种方式有局限,了解即可。
主要问题有二:
1、文件没有可读性,想手动改,没有相应工具不可能;
2、类的结构一旦发生变化,读已有的数据就会报错。
以后会推荐一个较好用的文件串行化。
范例是WinForm的
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
namespace Serializable
{
public partial class Form1 : Form
{
private Person person;
private string filePath;
private string fileDirectory;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
filePath = Path.Combine(Environment.CurrentDirectory, "Config\\Person.dat");
fileDirectory = Path.Combine(Environment.CurrentDirectory, "Config");
if (!Directory.Exists(fileDirectory))
{
Directory.CreateDirectory(fileDirectory);
}
if (!File.Exists(filePath))
{
return;
}
using (Stream stream = File.OpenRead(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
person = formatter.Deserialize(stream) as Person;
}
this.tbName.Text = person.Name;
this.nudAge.Value = person.Age;
}
private void btnSave_Click(object sender, EventArgs e)
{
string name = this.tbName.Text;
if (string.IsNullOrEmpty(name))
{
MessageBox.Show("姓名不能为空");
return;
}
int age = Convert.ToInt32(this.nudAge.Value);
if (age<=0 || age>200)
{
MessageBox.Show("年龄的值不对");
return;
}
if (person == null)
{
person = new Person();
}
person.Name = name;
person.Age = age;
if (File.Exists(filePath))
{
File.Delete(filePath);
}
using (Stream stream = File.Create(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, person);
}
}
}
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}