This documentation is archived and is not being maintained.

Code: Reading Class Data from an XML File (Visual C#)

Visual Studio .NET 2003

This example reads the data stored in an object in the IntroToVCS.xml file using the Deserialize method of the XmlSerializer class.

Example

public class Book
{
   public string title;

   static void Main()
   {
      Book introToVCS  = new Book();
      System.Xml.Serialization.XmlSerializer reader = new
         System.Xml.Serialization.XmlSerializer(introToVCS.GetType());

      // Read the XML file.
      System.IO.StreamReader file= 
         new System.IO.StreamReader("c:\\IntroToVCS.xml");

      // Deserialize the content of the file into a Book object.
      introToVCS = (Book) reader.Deserialize(file);
      System.Windows.Forms.MessageBox.Show(introToVCS.title,
         "Book Title");
   }
}

Compiling the Code

You can compile the example directly using the command line, or paste the code into a console application using the Visual Studio IDE. In the latter case, you must reference the System.Windows.Forms.dll file.

Replace "c:\\IntroToVCS.xml" with the actual file name.

Robust Programming

The following conditions may cause an exception:

See Also

Code: Writing Class Data to an XML File (Visual C#) | File Access Through StreamReader and StreamWriter Classes | StreamWriter Class | General Language Example Topics

Show: