I'm trying to read a binary file, using memorystream and filestream and a struct, with the code below:
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();
The GameSaved struct looks like this:
[Serializable]
struct GameSaved
{
public int Num_Of_Saved_Game;
public string[] Name_Of_Saved_Game;
}
But the code throws an error
System.InvalidCastException: 'Specified cast is not valid.'
Edit: This is how I save my GameSaved struct:
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();
Could anyone please show me the way to solve the problems?
Best Regards
GameSaved newdata = (GameSaved)? - TheVillageIdiot