日期:2014-05-18 浏览次数:20827 次
XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem)); using (FileStream stream = File.Open("d:/123.txt", FileMode.Create)) { using (MemoryStream ms = new MemoryStream()) { OrderedItem i = new OrderedItem(); i.ItemName = "Widget1"; i.Description = "Regular Widget1"; i.Quantity = 10; i.UnitPrice = (decimal)2.30; serializer.Serialize(ms, i); int len = (int)ms.Length; stream.Write(BitConverter.GetBytes(len), 0, sizeof(int)); stream.Write(ms.ToArray(), 0, (int)ms.Length); } using (MemoryStream ms = new MemoryStream()) { OrderedItem i = new OrderedItem(); i.ItemName = "Widget2"; i.Description = "Regular Widget2"; i.Quantity = 10; i.UnitPrice = (decimal)2.30; serializer.Serialize(ms, i); int len = (int)ms.Length; stream.Write(BitConverter.GetBytes(len), 0, sizeof(int)); stream.Write(ms.ToArray(), 0, (int)ms.Length); } } var bytes = File.ReadAllBytes("d:/123.txt"); int index = 0; { int len = BitConverter.ToInt32(bytes, index); index += sizeof(int); using (MemoryStream ms = new MemoryStream(bytes, index, len)) { index += len; OrderedItem item = (OrderedItem)serializer.Deserialize(ms); } } { int len = BitConverter.ToInt32(bytes, index); index += sizeof(int); using (MemoryStream ms = new MemoryStream(bytes, index, len)) { index += len; OrderedItem item = (OrderedItem)serializer.Deserialize(ms); } }