Share via


How to: Write Class Data to an XML File

This example writes the data stored in an object to a sample file that is named IntroToVCS.xml by using 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 at a command prompt, or paste the code into a console application by using the Visual Studio IDE.

Robust Programming

The following conditions may cause an exception:

  • The file exists and is read-only.

  • The path name may be too long.

  • The disk may be full.

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

Concepts

Designing a User Interface in Visual C#

Other Resources

Accessing and Displaying Data

Visual C# Guided Tour