有三个对象,依次用二进制方式序列化到文件中,然后依次取出来。应该怎么做,第一个对象取出来成功了,但是取第二个对象的时候出现了错误:在分析完成之前遇到了流结尾
namespace ConsoleApplication5{ class Program { static void Main(string[] args) { Serialize(); Deserialize(); } static void Serialize() { A a = new A(); FileStream fs = new FileStream("DataFile.dat", FileMode.Open); BinaryWriter bw = new BinaryWriter(fs); MemoryStream ms = new MemoryStream(); // Construct a BinaryFormatter and use it to serialize the data to the stream. BinaryFormatter formatter = new BinaryFormatter(); try {
formatter.Serialize(ms, a); byte[] tem = new byte[(int)ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(tem, 0, (int)ms.Length); bw.Write(tem);
ms.Close(); ms = new System.IO.MemoryStream(); string p = "123"; formatter.Serialize(ms, p); byte[] tem1 = new byte[(int)ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(tem1, 0, (int)ms.Length); bw.Seek(0, SeekOrigin.End); bw.Write(tem1); bw.Flush(); bw.Close(); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { //fs.Close(); } } static void Deserialize() { FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter(); MemoryStream ms = new System.IO.MemoryStream(); byte[] a = new byte[145]; fs.Read(a, 0, 145); ms.Write(a, 0, 145);
object x = formatter.Deserialize(ms); Console.WriteLine(x.GetType());
byte[] b = new byte[27]; fs.Seek(145, SeekOrigin.Begin); fs.Read(b,0,27); ms.Write(b, 0, 27); x = formatter.Deserialize(ms); Console.WriteLine(x.GetType()); fs.Close();
} } [Serializable] class A { string x = "122"; }}
大话西游666
浏览 1033回答 11
11回答
函数式编程
最简单的方式,把三个对象组合成一个大对象:
public class Big {public A a;public B b;public C c;}