Serialize and deserialize objects to an XML file

This code shows the simplest way to automatically convert the information in an object to an XML file and back into an object. This is useful if you need to make information available web-server like on your server for other applications to pick it up. I just cut the significant parts out of Visual Studio so you'll have to build it into whatever form you like. Make sure you have write permissions on the directory.

from the .aspx file

       private void Button3_Click(object sender, System.EventArgs e)
           Book b = new Book();
           b.Title = "Windows Forms";
           b.Isbn = "728372837";

           XmlSerializer serializer = new XmlSerializer(typeof(Book));
           TextWriter tw = new StreamWriter(Server.MapPath("book1.xml"));

       private void Button4_Click(object sender, System.EventArgs e)
           XmlSerializer serializer = new XmlSerializer(typeof(Book));
           TextReader tr = new StreamReader(Server.MapPath("book1.xml"));
           Book b = (Book)serializer.Deserialize(tr);

           Title.Text = b.Title;
           Isbn.Text = b.Isbn;


using System;

namespace Serialize
   public class Book
       public string Title;
       public string Isbn;

You might also like...


Edward Tanguay Edward Tanguay updates his personal web site weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“A computer lets you make more mistakes faster than any other invention in human history, with the possible exceptions of handguns and tequila” - Mitch Ratcliffe