序列化常用于对象信息的转化以便持久化保存,下面是二进制和xml的相关操作
一、二进制
二进制的序列化需引用命名空间:System.Runtime.Serialization.Formatters.Binar
////// 对象序列化为二进制数据/// public static byte[] SerializeToBinary(object obj){ using (MemoryStream ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; bytes = new byte[ms.Length]; ms.Read(bytes, 0, bytes.Length); } return bytes;}
////// 二进制数据反序列化为对象/// public static T DeserializeWithBinary(byte[] bytes){ using (MemoryStream ms = new MemoryStream(bytes)) { ms.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); return (T)formatter.Deserialize(ms); }}
二、Xml
xml的序列化引进命名空间:System.Xml.Serialization
////// 对象序列化为Xml数据/// public static string SerializeToXml(object obj){ using (MemoryStream ms = new MemoryStream()) { XmlSerializer xml = new XmlSerializer(obj.GetType()); //序列化对象 xml.Serialize(ms, obj); ms.Position = 0; using (StreamReader sr = new StreamReader(ms)) { str = sr.ReadToEnd(); } } return str;}
////// Xml数据反序列化为对象/// public static T DeserializeWithXml(string xml){ using (StringReader sr = new StringReader(xml)) { XmlSerializer xmldes = new XmlSerializer(typeof(T)); return (T)xmldes.Deserialize(sr); }}
三、本地读写
public class FileReader : FileOperater{ ////// 读二进制内容 /// public byte[] ReadBinary(string path) { if (!File.Exists(path)) return null; byte[] bytes = null; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { bytes = new byte[fs.Length]; fs.Read(bytes, 0, bytes.Length); } return bytes; } ////// 读Xml内容 /// public string ReadXml(string path) { if (!File.Exists(path)) return null; string content = ""; using (StreamReader stream = new StreamReader(path, Encoding.Default, true)) { content = stream.ReadToEnd(); } return content; }}
public class FileWriter : FileOperater{ ////// 写Xml内容 /// public void WriteXML(string path, string content) { if (!File.Exists(path)) return null; using (TextWriter txtWriter = new StreamWriter(path, false, Encoding.Default)) { txtWriter.Write(content); } } ////// 写二进制内容 /// public void WriteBinary(string path, byte[] bytes) { if (!File.Exists(path)) return null; using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) { fs.Write(bytes, 0, bytes.Length); } }}