标题应该清楚我正在尝试做什么 - 获取Entity Framework对象,将其序列化为字符串,将字符串保存在文件中,然后从文件加载文本并将其重新序列化为对象。嘿presto!
但当然它不起作用,否则我不会在这里。当我尝试重新编写时,我得到一个“输入流不是有效的二进制格式”错误,所以我显然在某处遗漏了某些东西。
这是我序列化和保存数据的方式:
string filePath = System.Configuration.ConfigurationManager.AppSettings["CustomersLiteSavePath"];
string fileName = System.Configuration.ConfigurationManager.AppSettings["CustomersLiteFileName"];
if(File.Exists(filePath + fileName))
{
File.Delete(filePath + fileName);
}
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, entityFrameWorkQuery.First());
string str = System.Convert.ToBase64String(memoryStream.ToArray());
StreamWriter file = new StreamWriter(filePath + fileName);
file.WriteLine(str);
file.Close();
正如您所料,这给了我一个很大的荒谬的文本文件。然后我尝试在别处重建我的对象:
CustomerObject = File.ReadAllText(path);
MemoryStream ms = new MemoryStream();
FileStream fs = new FileStream(path, FileMode.Open);
int bytesRead;
int blockSize = 4096;
byte[] buffer = new byte[blockSize];
while (!(fs.Position == fs.Length))
{
bytesRead = fs.Read(buffer, 0, blockSize);
ms.Write(buffer, 0, bytesRead);
}
BinaryFormatter formatter = new BinaryFormatter();
ms.Position = 0;
Customer cust = (Customer)formatter.Deserialize(ms);
然后我得到二进制格式错误。
我显然非常愚蠢。但是以什么方式?干杯, 马特
答案 0 :(得分:3)
当您保存它时,您(基于您最熟悉的原因)应用base-64 - 但是在阅读时没有应用base-64。 IMO,只需完全删除base-64,然后直接写入FileStream
。这也节省了必须在内存中缓冲它。
例如:
if(File.Exists(path))
{
File.Delete(path);
}
using(var file = File.Create(path)) {
BinaryFormatter ser = new BinaryFormatter();
ser.Serialize(file, entityFrameWorkQuery.First());
file.Close();
}
和
using(var file = File.OpenRead(path)) {
BinaryFormatter ser = new BinaryFormatter();
Customer cust = (Customer)ser.Deserialize(file);
...
}
作为附注,您可能会发现DataContractSerializer
为EF制作了比BinaryFormatter
更好的序列化程序。