How to: Write Object Data to an XML File (C# and Visual Basic)

This example writes the object from a class to an XML file using the XmlSerializer class.

Example

This code example defines a class named Book, creates an instance of the class, and uses XML serialization to write the instance to an XML file.

Code similar to this is available as an IntelliSense code snippet. In the Code Snippet Manager, it is located in XML. For more information, see Code Snippets.

Public Module XMLWrite

    Sub Main()
        WriteXML()
    End Sub 

    Public Class Book
        Public Title As String 
    End Class 

    Public Sub WriteXML()
        Dim overview As New Book
        overview.Title = "Serialization Overview" 
        Dim writer As New System.Xml.Serialization.XmlSerializer(GetType(Book))
        Dim file As New System.IO.StreamWriter(
            "c:\temp\SerializationOverview.xml")
        writer.Serialize(file, overview)
        file.Close()
    End Sub 
End Module
public class XMLWrite
{

   static void Main(string[] args)
    {
        WriteXML();
    }


    public class Book
    {
        public String title; 
    }


    public static void WriteXML()
    {
        Book overview = new Book();
        overview.title = "Serialization Overview";
        System.Xml.Serialization.XmlSerializer writer = 
            new System.Xml.Serialization.XmlSerializer(typeof(Book));

        System.IO.StreamWriter file = new System.IO.StreamWriter(
            @"c:\temp\SerializationOverview.xml");
        writer.Serialize(file, overview);
        file.Close();
    }
}

Compiling the Code

The class must have a public constructor without parameters.

Robust Programming

The following conditions may cause an exception:

Security

This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs Create access for the folder. If the file already exists, the application needs only Write access, a lesser privilege. Where possible, it is more secure to create the file during deployment, and only grant Read access to a single file, rather than Create access for a folder.

See Also

Tasks

How to: Read Object Data from an XML File (C# and Visual Basic)

Reference

StreamWriter

Other Resources

Serialization (C# and Visual Basic)

Serialization (C# and Visual Basic)