2011-02-18 10 views
7

El título debe dejar en claro lo que estoy tratando de hacer: obtener un objeto Entity Framework, serializarlo en una cadena, guardar la cadena en un archivo, luego cargar el texto del archivo y reserialize en un objeto. ¡Listo!Serializar objeto Entity Framework, guardar en archivo, leer y DeSerialize

Pero, por supuesto, no funciona, no estaría aquí. Cuando trato de reservar, aparece el error "La secuencia de entrada no está en un formato binario válido", así que obviamente me falta algo en alguna parte.

Éste es cómo serializar y guardar mis datos:

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(); 

Lo que me da un archivo de texto sin sentido grande, como era de esperar. Luego trato de reconstruir mi objeto en otro lugar:

  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); 

Y luego aparece el error de formato binario.

Obviamente estoy siendo muy estúpido. Pero, ¿de qué manera?

Saludos, Matt

Respuesta

3

Cuando lo has salvado, que tiene (por razones más conocidas a usted) aplicada en base 64 - pero no han aplicado base 64 al leerlo. IMO, solo suelta la base-64 por completo, y escribe directamente en el FileStream. Esto también ahorra tener que almacenarlo en la memoria.

Por ejemplo:

if(File.Exists(path)) 
    { 
     File.Delete(path); 
    } 
    using(var file = File.Create(path)) { 
     BinaryFormatter ser = new BinaryFormatter(); 
     ser.Serialize(file, entityFrameWorkQuery.First()); 
     file.Close(); 
    } 

y

 using(var file = File.OpenRead(path)) { 
     BinaryFormatter ser = new BinaryFormatter(); 
     Customer cust = (Customer)ser.Deserialize(file); 
     ... 
    }  

como nota al margen, es posible que DataContractSerializer hace una mejor serializador para EF que BinaryFormatter.

+0

Genial, gracias. ¡Y arregló mi código sin costo adicional! La conversión de Base64 demuestra los peligros de copiar otros bits de su código y volver a usarlos sin leerlos correctamente. –

Cuestiones relacionadas