此代码从 SQLite 反序列化对象。我从 DBinaryData (BLOB) 字段中获取序列化对象。但是获取 System.Runtime.Serialization.SerializationException: end of stream 在解析完成之前遇到。如何解决这个问题?
public void Dump()
{
try
{
const string databaseName = @"C:\Code\C#\WcfService\WcfService\mainDB.db3";
SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};", databaseName));
connection.Open();
try
{
SQLiteCommand command = new SQLiteCommand("INSERT into 'dump' ('DTime', 'DBinaryData') VALUES ('" + DateTime.Now.ToString() + "', '" + GetSerializedMessages() + "')", connection);
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
catch (Exception e)
{
Logger.Log(e.Message);
}
}
public void Restore()
{
try
{
const string databaseName = @"C:\Code\C#\WcfService\WcfService\mainDB.db3";
SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};", databaseName));
connection.Open();
try
{
SQLiteCommand command = new SQLiteCommand("SELECT * FROM dump ORDER BY DId DESC limit 1", connection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Queue<Message> deserializedData = GetDeserializedMessages((byte[])reader["DBinaryData"]);
var data = MergeQueueMessage(deserializedData);
Logger.Log(data.ToString());
}
}
finally
{
connection.Close();
}
}
catch (Exception e)
{
Logger.Log(e.Message);
}
}
public byte[] GetSerializedMessages()
{
byte[] result = null;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
try
{
lock (MessageQueue.Instance.Messages)
{
formatter.Serialize(memoryStream, MessageQueue.Instance.Messages);
}
result = new byte[memoryStream.GetBuffer().Length];
memoryStream.GetBuffer().CopyTo(result, 0);
}
catch (SerializationException e)
{
Logger.Log("Failed to serialize. Reason: " + e.Message);
}
finally
{
memoryStream.Close();
}
return result;
}
public Queue<Message> GetDeserializedMessages(byte[] source)
{
Queue<Message> messages = null;
using (MemoryStream memoryStream = new MemoryStream(source))
{
BinaryFormatter formatter = new BinaryFormatter();
messages = (Queue<Message>)formatter.Deserialize(memoryStream);
}
return messages;
}
private IEnumerable<Message> MergeQueueMessage(Queue<Message> source)
{
IEnumerable<Message> result = MessageQueue.Instance.Messages.Union(source, new EqualityComparator());
return result;
}