C# Xml database

I was thinking I needed a small footprint database the other day when coding a small app. If you need something to save small amount of data you can just serialize it to Xml file and back. There is your little database. Obviously not very usable for heavy load, but with a small amount of data it works just fine. There is not much involved lets take a look.

public class Car
    {
        public string Model = string.Empty;
        public int Year = 0;
        //
        public Car() {}
    }

        /// Reads car objects from xml file
        public static List<Car> readXML()
        {
            // Trap
            if (!File.Exists(XML_FILE)) return new List<Car>();

            // Deserialize, load from XML
            FileStream fs = new FileStream(XML_FILE, FileMode.Open);
            XmlReader reader = new XmlTextReader(fs);
            XmlSerializer ser = new XmlSerializer(typeof(List<Car>));
            List<Car> myList = (List<Car>)ser.Deserialize(reader);
            fs.Close();
            //
            return myList;
        }

        /// Writes car objects to xml file
        public static void writeXML(List<Car> plStocks)
        {
            // Now create the Xml
            XmlSerializer s = new XmlSerializer(typeof(List<Car>));
            TextWriter writer = new StreamWriter(XML_FILE);
            // Serializes the objects in list
            s.Serialize(writer, plStocks);
            // done, close the file
            writer.Close();
        }

2 Comments

  1. John Depue says:

    Another option for you to consider is SQLite, it is made for exactly what you are talking about. SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The library file you would include with your project is around 150k.

    Probably one of the most widely used databases in the world.

    Here is the link:
    http://www.sqlite.org/

    Your M$ .Net wrappers are found here:
    http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers

    This is what Firefox uses to store all its internal meta data, as well as your preferences.

  2. orn says:

    I will take a look, thanks for the pointer.

Leave a Reply