日期:2009-05-02 浏览次数:20456 次
/*
FileName: saveArrary2File.cs
Author : zhanghua
Date : 2005-8-27
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
class Class1
{
///<summary>
///应用程序的主入口点
///</summary>
[STAThread]
static void Main(string[] args)
{
//
//定义PurchaseOrder类型的数组对象obj, 设置其数组长度为2,
// 并在其中保存了用户要序列化的数据。
PurchaseOrder obj = new PurchaseOrder();
obj.ItemsOrders = new Item[2];
obj.ItemsOrders[0] = new Item();
obj.ItemsOrders[0].ItemID = "First";
obj.ItemsOrders[0].ItemPrice = 500.25M;
obj.ItemsOrders[1] = new Item();
obj.ItemsOrders[1].ItemID = "Second";
obj.ItemsOrders[0].ItemPrice = 66.88M;
//创建一个文件流对象stream,指向文件MyFile.bin
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("D:\\MyFile.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
//通过formatter对象以二进制格式将obj对象序列化后到文件MyFile.bin中
formatter.Serialize(stream,obj);
stream.Close();
}
//定义两个可序列化的类PurchaseOrder 和Item
[Serializable]
public class PurchaseOrder
{
public Item [] ItemsOrders;
}
[Serializable]
public class Item
{
public string ItemID;
public decimal ItemPrice;
}
}
/*
Summary : 通过本实例可以学习到如何将比较复杂的结构序列化到文件中
*/