How to: Save to and Load from Isolated Storage with LINQ to XML
Microsoft Silverlight will reach end of support after October 2021. Learn more.
In Silverlight you can load and save files by using classes defined in the System.IO.IsolatedStorage namespace. Other ways of loading files are:
By using XmlXapResolver to load files that are in the application's XAP package. For more information, see Working with XmlXapResolver.
By using XmlPreloadedResolver to load from pre-populate cache. For more information, see Working with XmlPreloadedResolver.
By using the asynchronous WebRequest to load files from URI locations. For more information, see How to: Load an XML File from an Arbitrary URI Location with LINQ to XML.
To configure a Silverlight Visual Studio project to run this example
Modify your page.xaml file so that it includes the following TextBlock element:
<TextBlock x:Name ="OutputTextBlock" Canvas.Top ="10" TextWrapping="Wrap"/>
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):
Imports System.IO Imports System.Xml.Linq Imports System.IO.IsolatedStorage
using System.IO; using System.Xml.Linq; using System.IO.IsolatedStorage;
Example
The following example obtains the isolated storage for the user. It then saves the file to an application's isolated storage and later loads the file from an isolated storage.
Dim srcTree As XDocument = _
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--This is a comment-->
<Root>
<Child1>data1</Child1>
<Child2>data2</Child2>
</Root>
Using isoStore As IsolatedStorageFile = _
IsolatedStorageFile.GetUserStoreForApplication()
Using isoStream As IsolatedStorageFileStream = _
New IsolatedStorageFileStream("myFile.xml", FileMode.Create, isoStore)
srcTree.Save(isoStream)
End Using
End Using
Using isoStore As IsolatedStorageFile = _
IsolatedStorageFile.GetUserStoreForApplication()
Using isoStream As IsolatedStorageFileStream = _
New IsolatedStorageFileStream("myFile.xml", FileMode.Open, isoStore)
Dim doc1 As XDocument = XDocument.Load(isoStream)
OutputTextBlock.Text = doc1.ToString()
End Using
End Using
XDocument doc = new XDocument(
new XComment("This is a comment"),
new XElement("Root",
new XElement("Child1", "data1"),
new XElement("Child2", "data2")
)
);
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("myFile.xml", FileMode.Create, isoStore))
{
doc.Save(isoStream);
}
}
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("myFile.xml", FileMode.Open, isoStore))
{
XDocument doc1 = XDocument.Load(isoStream);
OutputTextBlock.Text = doc1.ToString();
}
}