序列化
普通:
private void Button_Click(object sender, RoutedEventArgs e)
{
Person person = new Person();
person.age = 18;
person.name = "gg";
FileStream stream = new FileStream(@"C:\Users\whater\Desktop\person.txt", FileMode.CreateNew);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, person);
stream.Close();
}
[Serializable]
public class Person
{
public int age;
public string name;
public override string ToString()
{
return age + "=============" + name;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Person person = new Person();
FileStream stream = new FileStream(@"C:\Users\whater\Desktop\person.txt", FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
person=(Person)binaryFormatter.Deserialize(stream);
stream.Close();
MessageBox.Show( person.ToString());
}
xml序列化:
private void Button_Click(object sender, RoutedEventArgs e)
{
cat c = new cat();
c.age = 2;
c.name = "喵喵";
c.color = "red";
FileStream fs = new FileStream(@"C:\Users\whater\Desktop\cat.xml", FileMode.CreateNew);
SoapFormatter soap = new SoapFormatter();
soap.Serialize(fs, c);
fs.Close();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
FileStream fs = new FileStream(@"C:\Users\whater\Desktop\cat.xml", FileMode.Open);
SoapFormatter soap = new SoapFormatter();
cat c = new cat();
c=(cat)soap.Deserialize(fs);
MessageBox.Show(c.age+"=="+c.color+"=="+c.name);
}
}
[Serializable]
public class cat
{
public string name;
public int age;
public string color;
}