This article demonstrates the use of Isolated Storage
in Silverlight. In this article I will explain how to save and load data using
Isolated Storage.
What is Isolated Storage?
Isolated Storage is like cookies which provide the ability to
store data on client between application invocations but unlike cookies
Isolated Storage is full-fledged virtual file system, it provides the
application ability to Create, Read, Write, Delete and enumerate files and
directories inside the virtual file system.
First of all make a new Silverlight project and add assembly
reference "System.XML.Linq" using Add Reference.
Now add two button on page first button for save content in
IsolatedStorage and second for load data
from IsolatedStorage.
MainPage.xaml
<Grid x:Name="LayoutRoot"
Background="White" Margin="0,0,8,0">
<TextBlock x:Name ="TechnologiesTextBlock" Canvas.Top
="10" TextWrapping="Wrap"
Margin="10,37,10,8"/>
<Button Content="Save in
Isolated Storage" Height="23"
HorizontalAlignment="Left" Margin="8,10,0,0" x:Name="btnSave"
VerticalAlignment="Top" Width="169" Click="btnSave_Click"
/>
<Button Content="Load
from Isolated Storage" Height="23"
HorizontalAlignment="Right" Margin="0,10,25,0" x:Name="btnLoad"
VerticalAlignment="Top" Width="180" RenderTransformOrigin="2.013,-0.478" Click="btnLoad_Click"
/>
</Grid>
MainPage.xaml.cs
Add these three namespace
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
// Save button click event
private void
btnSave_Click(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
XDocument xDocument = new
XDocument(
new
XComment("Technologies"),
new
XElement("Web",
new XElement("ASPDOTNET", "ASPDOTNET"),
new XElement("Silverlight", "Silverlight"),
new XElement("WebDesign", "WebDesign"),
new XElement("WebServices", "WebServices")
)
);
using
(IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isolatesFileStream =
new
IsolatedStorageFileStream("CSharpCornerTechnologies.xml", FileMode.Create, isolatedStorageFile))
{
xDocument.Save(isolatesFileStream);
MessageBox.Show("Data saved successlly");
}
}
}
// Load button click event.
private void btnLoad_Click(object
sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
using
(IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using
(IsolatedStorageFileStream
isolatesFileStream = new IsolatedStorageFileStream("CSharpCornerTechnologies.xml",
FileMode.Open, isolatedStorageFile))
{
XDocument
xDocument = XDocument.Load(isolatesFileStream);
TechnologiesTextBlock.Text
= xDocument.ToString();
}
}
}
Now
time to run the application.
Image
1.
Click
on Save button:
Image
2.
Now
click on Load button:
Image
3.
That's
all. Questions or comments are most welcome in c-sharpcorner comments section.
For more information I have attached my sample application.