This documentation is archived and is not being maintained.

Code: Writing Class Data to an XML File (Visual C#)

Visual Studio .NET 2003

This example writes the data stored in an object to the IntroToVCS.xml by means of the Serialize method of the XmlSerializer class.

Example

public class Book
{
   public string title;

   static void Main()
   {
      Book introToVCS = new Book();
      introToVCS.title = "Intro to Visual CSharp";
      System.Xml.Serialization.XmlSerializer writer = 
         new System.Xml.Serialization.XmlSerializer(introToVCS.GetType());
      System.IO.StreamWriter file =
         new System.IO.StreamWriter("c:\\IntroToVCS.xml");

      writer.Serialize(file, introToVCS);
      file.Close();
   }
}

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.

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

Robust Programming

The following conditions may cause an exception:

Security

This example creates a new file, if the file does not already exist. If the file already exists, the application overwrites it.

See Also

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

Show: