How to: Save XMLWriter Content to Isolated Storage

How to: Save XMLWriter Content to Isolated Storage


This topic shows how to use the Microsoft .NET Framework for Silverlight to save XmlWriter content to an isolated storage file.

To configure a Silverlight Visual Studio project to run this example

  1. Modify your page.xaml file so that it includes the following TextBlock element:

    <TextBlock x:Name ="OutputTextBlock" Canvas.Top ="10" TextWrapping="Wrap"/>
  2. In the page.xaml.cs (page.xaml.vb in Visual Basic) source file for your application, add the following using statements (Imports in Visual Basic):

    using System.Xml;
    using System.IO;
    using System.Text;
    using System.IO.IsolatedStorage;

The code example does the following:

  • Obtains the isolated storage for the user.

  • Creates a new file in the isolated storage.

  • Uses the stream writer and an XmlWriterSettings object to create a new XmlWriter instance.

  • Writes content to the XmlWriter and calls the Flush method so that the content of XmlWriter content is written to the isolated storage.

  • Uses StreamReader to read the content of the file, and then writes the content to the page.

  • Deletes the file.

using (IsolatedStorageFile isoStore =

    // Create new file
    using (IsolatedStorageFileStream isoStream =
        new IsolatedStorageFileStream("IsoStoreFile.xml",
            FileMode.Create, isoStore))
        // Write to the Isolated Storage for the user.
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        // Create an XmlWriter.
        using (XmlWriter writer = XmlWriter.Create(isoStream, settings))

            writer.WriteComment("sample XML document");

            // Write an element (this one is the root).

            // Write the namespace declaration.
            writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");

            // Write the genre attribute.
            writer.WriteAttributeString("genre", "novel");

            // Write the title.
            writer.WriteString("The Handmaid's Tale");

            // Write the price.
            writer.WriteElementString("price", "19.95");

            writer.WriteStartElement(null, "ISBN", "urn:samples");

            // Write the style element (shows a different way to handle prefixes).
            writer.WriteElementString("style", "urn:samples", "hardcover");

            // Write the close tag for the root element.

            // Write the XML to the file.
    // Open the file again for reading.
    using (StreamReader reader =
                    new StreamReader(isoStore.OpenFile("IsoStoreFile.xml", FileMode.Open)))
        OutputTextBlock.Text = reader.ReadToEnd();

    // Delete the IsoStoreFile.xml file.

Community Additions

© 2015 Microsoft