首页 > > > C# 怎么序列化多个不同的对象在文件内
C# 怎么序列化多个不同的对象在文件内,然后依次反序列化取出。在线等求指教
有三个对象,依次用二进制方式序列化到文件中,然后依次取出来。应该怎么做,第一个对象取出来成功了,但是取第二个对象的时候出现了错误:在分析完成之前遇到了流结尾
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";
}
}来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1976/viewspace-3147602/ ,如需转载,请注明出处,否则将追究法律责任。