using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; using System.Runtime.Serialization.Formatters.Binary; /**////<summary> /// ClassToSerialize 的摘要说明 ///</summary> [Serializable] publicclass ClassToSerialize { publicint id =100; publicstring name ="Name"; [NonSerialized] publicstring Sex ="男"; }
下面是串行化和反串行化的方法:
publicvoid SerializeNow() { ClassToSerialize c =new ClassToSerialize(); FileStream fileStream =new FileStream("c:\\temp.dat", FileMode.Create); BinaryFormatter b =new BinaryFormatter(); b.Serialize(fileStream, c); fileStream.Close(); } publicvoid DeSerializeNow() { ClassToSerialize c =new ClassToSerialize(); c.Sex ="kkkk"; FileStream fileStream =new FileStream("c:\\temp.dat", FileMode.Open, FileAccess.Read, FileShare.Read); BinaryFormatter b =new BinaryFormatter(); c = b.Deserialize(fileStream) as ClassToSerialize; Response.Write(c.name); Response.Write(c.Sex); fileStream.Close(); }
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml.Serialization; [Serializable] publicclass Person { privatestring name; publicstring Name { get { return name; } set { name = value; } } publicstring Sex; publicint Age =31; public Course[] Courses; public Person() { } public Person(string Name) { name = Name; Sex ="男"; } } [Serializable] publicclass Course { publicstring Name; [XmlIgnore] publicstring Description; public Course() { } public Course(string name, string description) { Name = name; Description = description; } }