Members

Technology Zones

Articles

Hosted By

MaximumASP

Info

Rated
Read 51,129 times

Related Categories

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

       //serialize
       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"));
           serializer.Serialize(tw,b);
           tw.Close();
       }


       //deserialize
       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);
           tr.Close();

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

Book.cs

using System;

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

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

Comments