title: System.InvalidCastException: 'Specified cast is not valid.'
body: <p>I'm trying to read a binary file, using memorystream and filestream and a struct, with the code below: </p>
  
  <pre><code>BinaryFormatter formatter = new BinaryFormatter();
  MemoryStream mStream = new MemoryStream();
  byte[] buffer = null;
  long numBytes = new FileInfo(filename1).Length;
  FileStream fs = new FileStream(filename1, FileMode.Open, FileAccess.Read);
  BinaryReader br = new BinaryReader(fs);
  buffer = br.ReadBytes((int)numBytes);
  mStream.Write(buffer, 0, buffer.Length);
  mStream.Position = 0;
  GameSaved newdata = (GameSaved)formatter.Deserialize(mStream);
  mStream.Close();
  fs.Close();
  fs.Dispose();
  mStream.Dispose();
  </code></pre>
  
  <p>The <code>GameSaved</code> struct looks like this: </p>
  
  <pre><code>[Serializable]
  struct GameSaved
  {
      public int Num_Of_Saved_Game;
      public string[] Name_Of_Saved_Game;
  }
  </code></pre>
  
  <p>But the code throws an error</p>
  
  <blockquote>
    <p>System.InvalidCastException: 'Specified cast is not valid.'</p>
  </blockquote>
  
  <p>Edit: This is how I save my <code>GameSaved</code> struct: </p>
  
  <pre><code>buffer = null;
  formatter = new BinaryFormatter();
  mStream = new MemoryStream();
  formatter.Serialize(mStream, newdata);
  buffer = mStream.ToArray();
  mStream.Close();
  filename = "name.sav";
  curFile = @"c:\C#\Try_To_Save_MS\Try_To_Save_MS\bin\Debug\name.sav";
  
  if (File.Exists(curFile))
      File.Delete(curFile);
  
  fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
  fs.Write(buffer, 0, (int)buffer.Length);
  fs.Dispose();
  mStream.Dispose();
  </code></pre>
  
  <p>Could anyone please show me the way to solve the problems? </p>
  
  <p>Best Regards</p>