System.InvalidCastException:'指定的强制转换无效。'

时间:2018-04-01 07:55:32

标签: c#

我正在尝试使用内存流和文件流以及结构读取二进制文件,代码如下:

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

GameSaved结构如下所示:

[Serializable]
struct GameSaved
{
    public int Num_Of_Saved_Game;
    public string[] Name_Of_Saved_Game;
}

但代码会抛出错误

  

System.InvalidCastException:'指定的强制转换无效。'

编辑:这是我保存GameSaved结构的方式:

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

有谁能告诉我解决问题的方法?

最好的问候

1 个答案:

答案 0 :(得分:1)

您应该使用BinaryFormatter.Serialize方法来序列化您的对象。在你的代码中,你写了一个缓冲区,但可能不会做同样的事情

您的数据序列化样本可以用这种方式编写

GameSaved reloaded = new GameSaved();
void Main()
{
    GameSaved game = new GameSaved();
    game.Num_Of_Saved_Game = 2;
    game.Name_Of_Saved_Game = new string[] {"game1", "game2"};

    Serialize(@"e:\temp\serialize.bin", game);
    Deserialize(@"e:\temp\serialize.bin");

    Console.WriteLine("Games:" + reloaded.Num_Of_Saved_Game);
    foreach(string s in reloaded.Name_Of_Saved_Game)
        Console.WriteLine(s);
}

void Deserialize(string filename1)
{
    BinaryFormatter formatter = new BinaryFormatter();
    using(FileStream fs = new FileStream(filename1, FileMode.Open, FileAccess.Read))
        reloaded = (GameSaved)formatter.Deserialize(fs);
}
void Serialize(string filename1, GameSaved game)
{
    BinaryFormatter formatter = new BinaryFormatter();
    using (FileStream fs = new FileStream(filename1, FileMode.OpenOrCreate, FileAccess.Write))
        formatter.Serialize(fs, game);

}
[Serializable]
struct GameSaved
{
    public int Num_Of_Saved_Game;
    public string[] Name_Of_Saved_Game;
}