保存或读取文件,出了什么问题?
这会创建空文件。
我很困惑,请告诉我如何正确地做到这一点。正如你所看到的,我试图保存一个类然后再读回它们的数组。
public void savePlayers()
{
string path = @"scores.dat";
if (File.Exists(path))
{
File.Delete(path);
}
try
{
using (FileStream fs = File.Create(path))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, player.players);
fs.Close();
}
}
catch
{
MessageBox.Show("Failed to save data", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void readPlayers()
{
string path = @"scores.dat";
player.players.Clear();
try
{
using (FileStream fs = File.OpenRead(path))
{
BinaryFormatter formatter = new BinaryFormatter();
player.players.Add((Player)formatter.Deserialize(fs));
fs.Close();
}
}
catch
{
MessageBox.Show("Failed to read stats file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
答案 0 :(得分:1)
您正在保存player.players
集合,并且您正在尝试加载单个播放器(player.players.Add((Player)formatter.Deserialize(fs));
)。这是不正确的。
这取决于您必须在装载侧(反序列化)或保存侧(序列化)修复此问题。
// Saving
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, player.players.Count); // or Count(), Length, depends on your list, collection,...
for each (Player pl in player.players)
{
formatter.Serialize(fs, pl);
}
fs.Close();
// Loading
BinaryFormatter formatter = new BinaryFormatter();
int count = (Int32) formatter.Deserialize(fs);
for (int i = 0; i < count; i++)
{
player.players.Add((Player)formatter.Deserialize(fs));
}
fs.Close();
并且Player
类必须标记为[Serializable]
,请检查它是否具有此属性。