摘要:
关键词:
using
System;
using
System.IO;
using
System.Collections;
using
System.Runtime.Serialization.Formatters.Binary;
using
System.Runtime.Serialization;

public
class
App

{
[STAThread]
static void Main()

{
Serialize();
Deserialize();
}

static void Serialize()

{
ArrayList TestList = new ArrayList();
for(int i = 1;i<=3;i++)

{
TestNode testNode = new TestNode(DateTime.Now.ToString(),i.ToString());
testNode.TestSubNode.Name = "Sub"+i.ToString();
testNode.TestSubNode.Number = "Sub"+DateTime.Now.ToString();
TestList.Add(testNode);
}

// To serialize the ArrayList and its key/value pairs,
// you must first open a stream for writing.
// In this case, use a file stream.
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
try

{
// formatter.Serialize(fs, addresses);
formatter.Serialize(fs, TestList);
}
catch (SerializationException e)

{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally

{
fs.Close();
}
}

static void Deserialize()

{

ArrayList TestList = new ArrayList();
// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
try

{
BinaryFormatter formatter = new BinaryFormatter();

// Deserialize the ArrayList from the file and
// assign the reference to the local variable.
//addresses = (ArrayList) formatter.Deserialize(fs);
TestList = (ArrayList)formatter.Deserialize(fs);
}
catch (SerializationException e)

{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally

{
fs.Close();
}

// To prove that the table deserialized correctly,
// display the key/value pairs.
foreach (TestNode de in TestList)

{
Console.WriteLine("TestNode({0}, {1}).\nTestSubNode({2},{3})", de.Number, de.Name,de.TestSubNode.Number,de.TestSubNode.Name);
}
}
}

[Serializable]
public
class
TestNode

{
private TestSubNode m_TestSubNode = new TestSubNode("","");
private string m_Number;
private string m_Name;
public TestNode(string number,string name)

{
m_Number =number;
m_Name = name;
}

public string Number

{

set
{m_Number=value;}

get
{return m_Number;}
}

public string Name

{

set
{m_Name=value;}

get
{return m_Name;}

}

public void SetTestSubNode(string number,string name)

{
m_TestSubNode.Number = number;
m_TestSubNode.Name = name;
}

public TestSubNode TestSubNode

{

set
{m_TestSubNode=value;}

get
{return m_TestSubNode;}

}


}
[Serializable]
public
class
TestSubNode

{
string m_Number;
string m_Name;
public TestSubNode(string number,string name)

{
m_Number =number;
m_Name = name;

}

public string Number

{

set
{m_Number=value;}

get
{return m_Number;}
}

public string Name

{

set
{m_Name=value;}

get
{return m_Name;}

}

}
转载于:https://www.cnblogs.com/MichaelLu/archive/2006/03/04/342660.html