Saving or reading a file, what is wrong?
This creates empty files.
I'm confused, please tell me how to do it properly. As you can see I'm trying to save a class and then read an array of them back.
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);
}
}