序列化实体框架对象,保存到文件,读取和DeSerialize

Bob*_*way 7 .net serialization entity-framework

标题应该清楚我要做的事情 - 获取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();
Run Code Online (Sandbox Code Playgroud)

这给了我一个很大的荒谬的文本文件,正如你所期望的那样.然后我尝试在别处重建我的对象:

            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);
Run Code Online (Sandbox Code Playgroud)

然后我得到二进制格式错误.

我显然非常愚蠢.但是以什么方式?

干杯,马特

Mar*_*ell 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();
    }
Run Code Online (Sandbox Code Playgroud)

     using(var file = File.OpenRead(path)) {
         BinaryFormatter ser = new BinaryFormatter();
         Customer cust = (Customer)ser.Deserialize(file);
         ...
    }     
Run Code Online (Sandbox Code Playgroud)

作为旁注,您可能会发现DataContractSerializerEF 的序列化器比BinaryFormatter.