創建Man.csthis
using System.Xml.Serialization;spa
///<summary>code
///Man 的摘要說明orm
///</summary>xml
[Serializable]對象
public class Manblog
{get
public Man() { string
}it
[XmlElement("Man_Age")]
public int Age
{
get;
set;
}
public string Name
{
get;
set;
}
public string tel
{
get;
set;
}
public Man(int Age, string Name ,string tel)
{
this.Age = Age;
this.Name = Name;
this.tel = tel;
}
public string Show()
{
return String.Format(" Name : {0} Age: {1} tel :{2}", this.Name, this.Age,this.tel);
}
public void AddData(int Age, string Name, string tel)
{
this.Age = Age;
this.Name = Name;
this.tel = tel;
}
}
1.二進制格式序列化
首先引入
using System.Runtime.Serialization.Formatters.Binary;
而後經過
string Path = "C:\\man.text";
Man m=new Man (18,"小王1","18618618618");
FileStream fs = new FileStream(Path, FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs,m);
fs.Close();
二進制序列化反序列化
string Path = "C:\\man.text";
Man m = null;
FileStream fs = new FileStream(Path,FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
m = formatter.Deserialize(fs) as Man ;//
fs.Close();
return m.Show();
2.XML序列化
string Path = "C:\\man.xml";
Man m = new Man();
m.AddData(18, "小王333", "18618618618");
using (StreamWriter fs = new StreamWriter (Path))
{
XmlSerializer xmlSerializer = new XmlSerializer(m.GetType());
xmlSerializer.Serialize(fs, m);
}
xml反序列化
string Path = "C:\\man.xml";
Man m = new Man ();
FileStream fs = new FileStream(Path,FileMode.Open);
XmlSerializer xmlSerializer = new XmlSerializer(m.GetType());
m = xmlSerializer.Deserialize(fs) as Man ;//
fs.Close();
return m.Show();
插曲: 能夠經過 [NonSerialized] 對對象中的的部分數據取消序列化 作到部分暴露
若是聲明一個類 而沒有共有字段 那麼這個類進行xml序列化的時候 將沒法把數據寫入xml文件
public class XMLserializeHelp { public static void Serialize<T>(string path, T t) where T:class { using (StreamWriter sw = new StreamWriter(path)) { XmlSerializer xml = new XmlSerializer(t.GetType()); xml.Serialize(sw, t); } } public static T Deserialize<T>(string path) where T:class { T t = default(T); FileStream fs = new FileStream(path, FileMode.Open); XmlSerializer xmlSerializer = new XmlSerializer(t.GetType()); t = xmlSerializer.Deserialize(fs) as T; fs.Close(); return t; } }