Thursday, 8 September 2011

Simple XML based C# Database

public class DatabaseMgr
{
  public Database Database { get; set; }
  private static DatabaseMgr instance;
  private DatabaseMgr() { }
  public static DatabaseMgr Instance
  {
    get
    {
      if (instance == null)
      {
        instance = new DatabaseMgr();
      }
      return instance;
    }
  }
  //use temp path
  private static string PATH = Path.Combine(Path.GetTempPath(), "UserDatabase.xml");
  public void Reload()
  {
    if (File.Exists(PATH))
    {
      XmlSerializer xs = new XmlSerializer(typeof(Database));
      using (TextReader reader = new StreamReader(PATH))
      {
        Database = (Database)xs.Deserialize(reader);
        reader.Close();
      }
    }
    else
    {
      Database = new Database();                
    }
  }
  public void Save()
  {
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Database));
    using (TextWriter writer = new StreamWriter(PATH))
    {
      xmlSerializer.Serialize(writer, Database);
      writer.Close();
    }
  }
}
[Serializable]
public class Database
{
  public Database()
  {
    Users = new List<User>();            
  }
  [XmlArray]
  [XmlArrayItem(ElementName = "User")]
  public List<User> Users { get; set; }
}
[Serializable]
public class User
{
  [XmlElement]
  public string Name { get; set; }
  [XmlElement]
  public int Age { get; set; }
}
[Test]
public void Test()
{
  DatabaseMgr.Instance.Reload();
  DatabaseMgr.Instance.Database.Users.Add(new User() { Name = "John", Age = 25 });
  DatabaseMgr.Instance.Save();
  foreach (var user in DatabaseMgr.Instance.Database.Users)
  {
    Console.WriteLine("{0}=>{1}",user.Name,user.Age);
  }
}

No comments:

Post a Comment