Home > Articles > Programming > Windows Programming

Like this article? We recommend

Like this article? We recommend

Serializing Objects to a Stream

The text in Listing 2 describes an array of Customer objects. Each property that had an underlying value was serialized unless we specifically used the XmlIgnore attribute or the property contained a null value. How did we create the file? The answer is that we serialized the data to a FileStream. The code that produced the customers.xml file—shown in Listing 2—is provided in Listing 3.

Listing 3—Serializing an Array of Objects to a Stream

// using System.IO;
// using System.Xml.Serialization;
XmlSerializer serializer =
 new XmlSerializer(typeof(Customer[]));

FileStream stream =
 new FileStream("c:\\temp\\customers.xml", FileMode.CreateNew);
serializer.Serialize(stream, customers);

The first two comments indicate the namespaces that contain the FileStream and XmlSerializer, respectively. The first statement indicates that we want to serialize an array of Customer objects. The second statement constructs an instance of the FileStream object, providing a filename and file mode.

NOTE

We use the double backslash (\\) because a single backslash (\) in C# is an escape; alternatively, we could use the @ symbol in front of the file path, instructing the compiler not to escape the backslash.

Finally, we invoke XmlSerializer.Serialize method, passing the stream and the object representing our array of customers. The end result is the XML file shown earlier in Listing 2. (We could have used another kind of stream, such as a MemoryStream, to keep the XML in memory.)

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.