//gmcs Game.cs Main.cs /out:Main.exe
using System;
using System.IO;
using System.Xml.Serialization;
namespace rootsilver.serialization{
public class Test{
public static void Main(){
Console.WriteLine("Starting new game ...");
Game game = new Game();
game.BoardSize = 3;
game.Move(1, 1, "X");
game.Move(2, 2, "O");
game.Move(3, 3, "X");
game.Move(3, 1, "O");
game.Move(1, 3, "O");
game.PrintBoard();
Console.WriteLine();
Console.WriteLine("Saving game (serializing to file) ...");
string savedGameFile = SaveGame(game);
Console.WriteLine("Loading saved game (deserializing from file) ...");
Console.WriteLine();
Game game2 = LoadGame(savedGameFile);
game2.PrintBoard();
}
public static Game LoadGame(string filePath) {
Game game = null;
using (Stream stream = File.Open(filePath, FileMode.Open)) {
XmlSerializer serializer = new XmlSerializer(typeof(Game));
game = (Game)serializer.Deserialize(stream);
}
return game;
}
public static String SaveGame(Game game) {
string filePath = typeof(Game).ToString() + ".xml";
using (Stream stream = File.Open(filePath, FileMode.Create)) {
XmlSerializer serializer = new XmlSerializer(typeof(Game));
serializer.Serialize(stream, game);
}
return filePath;
}
}
}
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace rootsilver.serialization{
[Serializable]
public class Game{
//(multi-dimensional arrays can not be serialized)
private String[] board;
private int boardWidth;
private int boardSquareCount;
//xml serialization requires a default constructor
public Game() { }
public int BoardSize{
get {
return this.boardWidth;
}
set {
this.boardWidth = value;
this.boardSquareCount = boardWidth * boardWidth;
this.board = new String[this.boardSquareCount];
this.InitializeBoard(".");
}
}
public String[] Board{
get { return board; }
//set will get called by the deserializer
set { this.board = value; }
}
private void InitializeBoard(string defaultValue){
for(int i = 0; i < this.boardSquareCount; i++){
this.board[i] = defaultValue;
}
}
public void Move(int x, int y, string move){
--x;
--y;
int square = x + ( y + (y * (this.boardWidth - 1)));
this.board[square] = move;
}
public void PrintBoard(){
Console.WriteLine("---------");
for(int i = 0; i < this.boardSquareCount; i++){
if(i > 0 && (i % this.boardWidth == 0) )
Console.WriteLine();
Console.Write(this.board[i] + " ");
}
Console.WriteLine();
Console.WriteLine("---------");
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Game xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<BoardSize>3</BoardSize>
<Board>
<string>X</string>
<string>.</string>
<string>O</string>
<string>.</string>
<string>O</string>
<string>.</string>
<string>O</string>
<string>.</string>
<string>X</string>
</Board>
</Game>
Listed below are links to blogs that reference this entry: Saving and Loading objects: Serialization using System.Xml.Serialization.
TrackBack URL for this entry: http://www.rootsilver.com/mt-tb.cgi/100
Leave a comment