title: Serialize Entity Framework object, save to file, read and DeSerialize
body: <p>The title should make it clear what I'm trying to do - get an Entity Framework object, serialize it into a string, save the string in a file, then load the text from the file and reserialize it into an object. Hey presto! </p>
  
  <p>But of course it doesn't work else I wouldn't be here. When I try to reserialise I get an "The input stream is not in a valid binary format" error so I'm obviously missing something somewhere.</p>
  
  <p>This is how I serialise and save my data:</p>
  
  <pre><code> 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();
  </code></pre>
  
  <p>Which gives me a big nonsensical text file, as you'd expect. I then try and rebuild my object elsewhere:</p>
  
  <pre><code>            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);
  </code></pre>
  
  <p>And then I get the binary format error.</p>
  
  <p>I'm obviously being very stupid. But in what way?</p>
  
  <p>Cheers,
  Matt</p>