Serializing to File
Instead write it to console. Let's try to write it to file. We've learn to read from file using streamreader. Now, we can use streamwriter to do the opposite.
First, create a function to serialize the players to file in our Main class. It takes list of players and path to the filename.
public static void SerializePlayerToFile(List<Player> players, string fileName)
{
}
We could use our previous deserialize code. I am just copy paste the deserialize's code into serialize's.
public static void SerializePlayerToFile(List<Player> players, string fileName)
{
var players = new List<Player>();
var serializer = new JsonSerializer();
using (var reader = new StreamReader(fileName))
using (var jsonReader = new JsonTextReader(reader))
{
players = serializer.Deserialize<List<Player>>(jsonReader);
}
return players;
}
First, we don't need return value because it is void method. We don't need list of player too. Then, change other variables to writer.
public static void SerializePlayerToFile(List<Player> players, string fileName)
{
var serializer = new JsonSerializer();
using (var writer = new StreamWriter(fileName))
using (var jsonWriter= new JsonTextWriter(writer))
{
}
}
Now, we want serializer to serialize the player. Following the Serialize method, the best code should be like this.
public static void SerializePlayerToFile(List<Player> players, string fileName)
{
var serializer = new JsonSerializer();
using (var writer = new StreamWriter(fileName))
using (var jsonWriter= new JsonTextWriter(writer))
{
serializer.Serialize(jsonWriter, players);
}
}
The function is done. Back to our Main method to call the function.
var fileTopTen = Path.Combine(directory.FullName, "topten.json");
SerializePlayerToFile(topTenPlayers, fileTopTen);