将一个自定义的结构体写入到文件中去的方法

将一个自定义的结构体写入到文件中去的方法


using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
//using System.Runtime.Serialization.Formatters.Binary;

public class Test {
public static void Main() {

//Creates a new TestSimpleObject object.
TestSimpleObject obj = new TestSimpleObject();

Console.WriteLine("Before serialization the object contains: ");
obj.Print();

//Opens a file and serializes the object into it in binary format.
Stream stream = File.Open("data.xml", FileMode.Create);
SoapFormatter formatter = new SoapFormatter();

//BinaryFormatter formatter = new BinaryFormatter();

formatter.Serialize(stream, obj);
stream.Close();

//Empties obj.
obj = null;

//Opens file "data.xml" and deserializes the object from it.
stream = File.Open("data.xml", FileMode.Open);
formatter = new SoapFormatter();

//formatter = new Binary