|
|
[This topic is pre-release documentation and is subject to change in future releases of Microsoft Silverlight.]
Using Isolated Storage and Application Settings
Introduction
This QuickStart is a simple application that shows how to work with files and use application settings in isolated storage. In Silverlight, all I/O operations use isolated storage.
The application has the following controls:
-
Textbox controls for specifying a file name and adding text to a file.
-
Button controls for saving and deleting files.
-
A Button control for increasing the host's quota of isolated storage space.
-
A ListBox control that lists the files in the store.
-
TextBlock controls for labels, the store's status, and any runtime errors.
The new Silverlight System.IO.IsolatedStorage.ApplicationSettings class enables you to save settings (as key-value pairs) with an application as an alternative to using cookies. This QuickStart uses an application setting to limit the number of files that can be added to the isolated store.
Prerequisites (available from the Silverlight download site):
-
Silverlight version 2 Beta 1.
-
Microsoft Visual Studio 2008.
-
Silverlight Tools Beta 1 for Visual Studio 2008.
This topic also assumes that you have created a basic Silverlight project. (See Creating an Application for Silverlight for instructions.)
Creating the User Interface
The following XAML code uses a Grid control with eight rows and four columns for displaying Button, TextBlock, TextBox, and ListBox controls. Note how the FileContentBox control spans two columns and two rows to create a large box for typing text, and how the FileList control spans four rows for displaying the list of files.
The following table lists the events used by the application which are defined in the XAML.
|
Event
|
Event handler
|
Actions
|
|
Click event on the SaveFile button.
|
OnClickSaveFile
|
Creates a file in the isolated store, overwriting the file if it already exists.
|
|
Click event on the DeleteFile button.
|
OnClickDeleteFile
|
Deletes a file from the store and removes its name from the list.
|
|
SelectionChanged on the FileList list box.
|
ShowContent
|
Displays the file name and contents of the currently selected file in the list.
|
|
Click event on the IncreaseQuota button.
|
OnClickIncreaseQuota
|
Starts the process for increasing the space for isolated storage.
|
|
TextChanged event on the FileNameBox text box.
|
OnFileNameChange
|
Removes any selection from the FileList box because a new name is being entered.
|
To create the user interface
-
Add the following XAML for the Grid control to the Page.xaml file.
cs
<Grid x:Name="LayoutRoot" Background="White" ShowGridLines="False">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Isolated Storage" Margin="5,5,10,15"
FontFamily="Verdana" FontSize="14" FontWeight="Bold"
Foreground="#FF5C9AC9" Grid.Row="0" Grid.ColumnSpan="2"/>
<Button x:Name="SaveFile" Grid.Row="4" Grid.Column="2"
Margin ="5,5,0,0"
HorizontalAlignment="Center"
Foreground="Blue" Width="100" Click="OnClickSaveFile"
Content="Save File" ClickMode="Release" />
<Button x:Name="DeleteFile" Grid.Row="5" Grid.Column="3"
Margin="5,5,0,0"
HorizontalAlignment="Right"
Click="OnClickDeleteFile" Width="100" Content="Delete File"
ClickMode="Release"/>
<Button x:Name="IncreaseQuota" Grid.Row="7" Grid.Column="3"
Margin="5,5,0,0"
HorizontalAlignment="Right"
Click="OnClickIncreaseQuota" Width="100" Content="Increase Quota"
ClickMode="Release"/>
<TextBlock x:Name="FileNameLabel" Grid.Row="1" Grid.Column="0"
HorizontalAlignment="Right" FontSize="14"
Margin ="5,5,0,0" Text="File name:"/>
<TextBlock x:Name="ContentsLabel" Grid.Row="2" Grid.Column="0"
HorizontalAlignment="Right" FontSize="14"
Margin="5,5,0,0" Text="Contents:"/>
<TextBlock x:Name="JustForRowSpacing" Grid.Row="3" Grid.Column="0"/>
<TextBlock x:Name="Status" Grid.Row="6" Grid.Column="0"
FontSize="10" FontFamily="Courier New"
Grid.ColumnSpan="2"
HorizontalAlignment="Left"
Margin="5,5,0,0" Text="Status:"/>
<TextBlock x:Name="Alert" Grid.Row="7" Grid.Column="0"
FontSize="10" FontWeight="Bold"
Grid.ColumnSpan="2"
HorizontalAlignment="Left"
Margin="5,5,0,0" Text="Alert:"/>
<TextBox x:Name="FileNameBox" Grid.Row="1" Grid.Column="1"
TextChanged="OnFileNameChange"
HorizontalAlignment="Left"
Width="100"
Margin ="5,0,0,15" Text=""/>
<TextBox x:Name="FileContentBox" Grid.Row="2" Grid.Column="1"
HorizontalAlignment="Left"
Grid.ColumnSpan="2"
Grid.RowSpan="2"
Width="220"
Margin ="5,5,0,0" Text=""/>
<ListBox x:Name="FileList" Grid.Row="1" Grid.Column="3"
SelectionChanged="ShowContent"
Width="100" Height ="100"
Grid.RowSpan="4"
Margin ="10,0,0,0"/>
</Grid>
vb
<Grid x:Name="LayoutRoot" Background="White" ShowGridLines="False">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Isolated Storage" Margin="5,5,10,15"
FontFamily="Verdana" FontSize="14" FontWeight="Bold"
Foreground="#FF5C9AC9" Grid.Row="0" Grid.ColumnSpan="2"/>
<Button x:Name="SaveFile" Grid.Row="4" Grid.Column="2"
Margin ="5,5,0,0"
HorizontalAlignment="Center"
Foreground="Blue" Width="100" Click="OnClickSaveFile"
Content="Save File" ClickMode="Release" />
<Button x:Name="DeleteFile" Grid.Row="5" Grid.Column="3"
Margin="5,5,0,0"
HorizontalAlignment="Right"
Click="OnClickDeleteFile" Width="100" Content="Delete File"
ClickMode="Release"/>
<Button x:Name="IncreaseQuota" Grid.Row="7" Grid.Column="3"
Margin="5,5,0,0"
HorizontalAlignment="Right"
Click="OnClickIncreaseQuota" Width="100" Content="Increase Quota"
ClickMode="Release"/>
<TextBlock x:Name="FileNameLabel" Grid.Row="1" Grid.Column="0"
HorizontalAlignment="Right" FontSize="14"
Margin ="5,5,0,0" Text="File name:"/>
<TextBlock x:Name="ContentsLabel" Grid.Row="2" Grid.Column="0"
HorizontalAlignment="Right" FontSize="14"
Margin="5,5,0,0" Text="Contents:"/>
<TextBlock x:Name="JustForRowSpacing" Grid.Row="3" Grid.Column="0"/>
<TextBlock x:Name="Status" Grid.Row="6" Grid.Column="0"
FontSize="10" FontFamily="Courier New"
Grid.ColumnSpan="2"
HorizontalAlignment="Left"
Margin="5,5,0,0" Text="Status:"/>
<TextBlock x:Name="Alert" Grid.Row="7" Grid.Column="0"
FontSize="10" FontWeight="Bold"
Grid.ColumnSpan="2"
HorizontalAlignment="Left"
Margin="5,5,0,0" Text="Alert:"/>
<TextBox x:Name="FileNameBox" Grid.Row="1" Grid.Column="1"
TextChanged="OnFileNameChange"
HorizontalAlignment="Left"
Width="100"
Margin ="5,0,0,15" Text=""/>
<TextBox x:Name="FileContentBox" Grid.Row="2" Grid.Column="1"
HorizontalAlignment="Left"
Grid.ColumnSpan="2"
Grid.RowSpan="2"
Width="220"
Margin ="5,5,0,0" Text=""/>
<ListBox x:Name="FileList" Grid.Row="1" Grid.Column="3"
SelectionChanged="ShowContent"
Width="100" Height ="100"
Grid.RowSpan="4"
Margin ="10,0,0,0"/>
</Grid>
Creating the Code Behind
The page.xaml.cs or page.xaml.vb file contains code that does the following:
-
Sets the name of the subdirectory at the root of the isolated store that will contain the files created by the application.
-
Sets and gets an application setting that specifies the maximum number of files that the store should contain.
-
Populates the file lists with the names of any existing files.
-
Handles the events for creating, deleting, and showing file content.
To get the isolated store and list any existing files
-
Use the following code for the start Page class and its constructor.
cs
public partial class Page : UserControl
{
// Name of folder to create
// in the isolated storage root.
string subDirName = "AppFiles";
// Set the maximum number of files
// that can be added to the store
// (example of an application setting).
int maxFilesNum = 10;
ApplicationSettings appSettings = ApplicationSettings.Default;
public Page()
{
InitializeComponent();
// Add the setting if not already set.
if (!appSettings.Contains("MaxFiles"))
{
appSettings.Add("MaxFiles", maxFilesNum);
}
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
// Create a directory for the files
// if it doesn't already exist.
if (!store.DirectoryExists(subDirName))
{
store.CreateDirectory(subDirName);
}
// Determine existing files and add
// their names in the list box.
string[] filesInSubDir = store.GetFileNames(subDirName + "/*");
foreach (string fileName in filesInSubDir)
{
FileList.Items.Add(fileName);
}
// Clear alert text block
// and show store's statistics.
Alert.Text = "";
ShowStatistics(store);
}
}
catch (IsolatedStorageException ex)
{
Alert.Text = ex.Message;
}
}
vb
Partial Public Class Page
Inherits UserControl
' Name of folder to create
' in the isolated storage root.
Private subDirName As String = "AppFiles"
' Set the maximum number of files
' that can be added to the store
' (example of an application setting).
Private maxFilesNum As Integer = 10
Private appSettings As ApplicationSettings = ApplicationSettings.Default
Public Sub New()
MyBase.New()
InitializeComponent()
' Add the setting if not already set.
If Not appSettings.Contains("MaxFiles") Then
appSettings.Add("MaxFiles", maxFilesNum)
End If
Try
Using store As IsolatedStorageFile = _
IsolatedStorageFile.GetUserStoreForApplication()
' Create a directory for the files
' if it doesn't already exist.
If Not store.DirectoryExists(subDirName) Then
store.CreateDirectory(subDirName)
End If
' Determine existing files and add
' their names in the list box.
Dim filesInSubDir() As String = _
store.GetFileNames((subDirName + "/*"))
For Each fileName As String In filesInSubDir
FileList.Items.Add(fileName)
Next
' Clear alert text block
' and show store's statistics.
Alert.Text = ""
ShowStatistics(store)
End Using
Catch ex As IsolatedStorageException
Alert.Text = ex.Message
End Try
End Sub
To show current store statistics
-
Add the following method to the Page class. The event handlers call this method to show the store's quota size, available free space, and the current number of files.
cs
// This method displays storage space usage information.
private void ShowStatistics(IsolatedStorageFile store)
{
// Determine file count
string[] curFiles = store.GetFileNames(subDirName + "/*");
string spaceUsed = (store.Quota - store.AvailableFreeSpace).ToString();
string spaceAvailable = store.AvailableFreeSpace.ToString();
string curQuota = store.Quota.ToString();
Status.Text =
String.Format("Files: {0}\nQuota: {1} bytes\nAvail: {3} bytes\nUsed: {2} bytes",
curFiles.Length.ToString(), curQuota, spaceUsed, spaceAvailable);
}
vb
' This method displays storage space usage information.
Private Sub ShowStatistics(ByVal store As IsolatedStorageFile)
' Determine file count
Dim curFiles() As String = store.GetFileNames((subDirName + "/*"))
Dim spaceUsed As String = (store.Quota - store.AvailableFreeSpace).ToString
Dim spaceAvailable As String = store.AvailableFreeSpace.ToString
Dim curQuota As String = store.Quota.ToString
Status.Text = String.Format("Files: {0}" & vbLf & "Quota: {1} bytes" & _
vbLf & "Avail: {3} bytes" & vbLf & "Used: {2} bytes", _
curFiles.Length.ToString, curQuota, spaceUsed, spaceAvailable)
End Sub
To save a file to the store.
-
Add the following method to the Page class.
cs
// This method creates a new file if the
// file name is not already in the list.
private void OnClickSaveFile(object sender, RoutedEventArgs e)
{
// Get the application setting that
// specifies the maximum number of files
// that can be created in the isolated store.
int curMax = (int) appSettings["MaxFiles"];
// Do not continue if there is no file
// name specified or if adding another
// file would exceed the MaxFiles setting.
if (FileNameBox.Text == "" || FileList.Items.Count + 1 > curMax)
{
if (FileNameBox.Text == "")
{
Alert.Text = "File name required.";
}
else if (FileList.Items.Count + 1 > curMax)
{
Alert.Text = "Cannot exceed " + curMax.ToString() + " files.";
}
}
else
{
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
// If a file name is selected in the list
// use that file name, otherwise use
// the name in the file name text box.
string fileName = "";
if (FileList.SelectedIndex != -1)
{
fileName = FileList.SelectedItem.ToString();
}
else
{
fileName = FileNameBox.Text;
}
try
{
// Create the file, overwriting it if it already exists.
using (IsolatedStorageFileStream newFile =
store.CreateFile(System.IO.Path.Combine(subDirName, fileName)))
{
StreamWriter sw = new StreamWriter(newFile);
sw.Write(FileContentBox.Text);
// If a file is not selected in the list,
// use the file from the file name box.
if (FileList.SelectedIndex == -1)
{
// Don't add the file name
// if it is already in the list.
bool isInList = false;
for (int x = 0; x < FileList.Items.Count; x++)
{
if (FileList.Items[x].ToString().ToLower() ==
fileName.ToLower())
{
isInList = true;
break;
}
}
if (isInList == false)
{
FileList.Items.Add(fileName);
}
}
sw.Close();
// Clear text boxes and display
// store usage information.
FileNameBox.Text = "";
FileContentBox.Text = "";
Alert.Text = "";
FileList.SelectedIndex = -1;
ShowStatistics(store);
}
}
catch (IsolatedStorageException ex)
{
Alert.Text = ex.Message;
}
}
}
catch (IsolatedStorageException ex)
{
Alert.Text = ex.Message;
}
}
}
private void OnFileNameChange(object sender, RoutedEventArgs args)
{
// Remove any selection from the
// file list box because a new
// file name is being created.
FileList.SelectedIndex = -1;
}
vb
' This method creates a new file if the
' file name is not already in the list.
Private Sub OnClickSaveFile(ByVal sender As Object, _
ByVal e As RoutedEventArgs)
' Get the application setting that
' specifies the maximum number of files
' that can be created in the isolated store.
Dim curMax As Integer = CType(appSettings("MaxFiles"), Integer)
' Do not continue if there is no file
' name specified or if adding another
' file would exceed the MaxFiles setting.
If FileNameBox.Text = "" _
OrElse FileList.Items.Count + 1 > curMax Then
If FileNameBox.Text = "" Then
Alert.Text = "File name required."
ElseIf FileList.Items.Count + 1 > curMax Then
Alert.Text = ("Cannot exceed " _
+ (curMax.ToString + " files."))
End If
Else
Try
Using store As IsolatedStorageFile = _
IsolatedStorageFile.GetUserStoreForApplication()
' If a file name is selected in the list
' use that file name, otherwise use
' the name in the file name text box.
Dim fileName As String = FileNameBox.Text
If FileList.SelectedIndex <> -1 Then
fileName = FileList.SelectedItem.ToString
End If
Try
' Create the file, overwriting it if it already exists.
Using newfile As IsolatedStorageFileStream = _
store.CreateFile(System.IO.Path.Combine(subDirName, _
fileName))
Dim sw As StreamWriter = New StreamWriter(newfile)
sw.Write(FileContentBox.Text)
' If a file is not selected in the list,
' use the file from the file name box.
If (FileList.SelectedIndex = -1) Then
' Don't add the file name
' if it is already in the list.
Dim isinList As Boolean = False
Dim x As Integer = 0
Do While x < FileList.Items.Count
If FileList.Items(x).ToString.ToLower = _
fileName.ToLower Then
isinList = True
Exit Do
End If
x = (x + 1)
Loop
If (isinList = False) Then
FileList.Items.Add(fileName)
End If
End If
sw.Close()
' Clear text boxes and display
' store usage information.
FileNameBox.Text = ""
FileContentBox.Text = ""
Alert.Text = ""
FileList.SelectedIndex = -1
ShowStatistics(store)
End Using
Catch ex As IsolatedStorageException
Alert.Text = ex.Message
End Try
End Using
Catch ex As IsolatedStorageException
Alert.Text = ex.Message
End Try
End If
End Sub
Private Sub OnFileNameChange(ByVal sender As Object, _
ByVal args As RoutedEventArgs)
' Remove any selection from the
' file list box because a new
' file name is being created.
FileList.SelectedIndex = -1
End Sub
To delete a file from the store
-
Add the following method to the Page class.
cs
// This method removes a file from isolated storage.
private void OnClickDeleteFile(object sender, RoutedEventArgs e)
{
// Do not continue if a file is not selected.
if (FileList.SelectedIndex != -1)
{
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
string delFile = System.IO.Path.Combine(subDirName,
FileList.SelectedItem.ToString());
// Delete the file if it
// exists in the store.
if (store.FileExists(delFile))
{
try
{
store.DeleteFile(delFile);
// Remove the file name from the list.
FileList.Items.Remove(FileList.SelectedItem);
// Clear text boxes and display
// store usage information.
FileNameBox.Text = "";
FileContentBox.Text = "";
Alert.Text = "";
ShowStatistics(store);
}
catch (IsolatedStorageException ex)
{
Alert.Text = ex.Message;
}
}
}
}
catch (IsolatedStorageException ex)
{
Alert.Text = ex.Message;
}
}
else
{
Alert.Text = "Select a file to delete.";
}
}
vb
' This method removes a file from isolated storage.
Private Sub OnClickDeleteFile(ByVal sender As Object, _
ByVal e As RoutedEventArgs)
' Do not continue if a file is not selected.
If (FileList.SelectedIndex <> -1) Then
Try
Using store As IsolatedStorageFile = _
IsolatedStorageFile.GetUserStoreForApplication()
Dim delFile As String = _
System.IO.Path.Combine(subDirName, _
FileList.SelectedItem.ToString)
' Delete the file if it
' exists in the store.
If store.FileExists(delFile) Then
Try
store.DeleteFile(delFile)
' Remove the file name from the list.
FileList.Items.Remove(FileList.SelectedItem)
' Clear text boxes and display
' store usage information.
FileNameBox.Text = ""
FileContentBox.Text = ""
Alert.Text = ""
ShowStatistics(store)
Catch ex As IsolatedStorageException
Alert.Text = ex.Message
End Try
End If
End Using
Catch ex As IsolatedStorageException
Alert.Text = ex.Message
End Try
Else
Alert.Text = "Select a file to delete."
End If
End Sub
To show the contents of a selected file
-
Add the following method to the Page class.
cs
// This method displays the contents of selected file from the list.
private void ShowContent(object sender, SelectionChangedEventArgs args)
{
// Do not continue if a file is not selected.
if (FileList.SelectedIndex != -1)
{
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
string fileName = FileList.SelectedItem.ToString();
FileNameBox.Text = fileName;
try
{
using (IsolatedStorageFileStream curFile =
store.OpenFile(System.IO.Path.Combine(subDirName, fileName),
FileMode.Open, FileAccess.Read))
{
StreamReader sr = new StreamReader(curFile);
FileContentBox.Text = sr.ReadToEnd();
sr.Close();
}
}
catch (IsolatedStorageException ex)
{
Alert.Text = ex.Message;
}
}
}
catch (IsolatedStorageException ex)
{
Alert.Text = ex.Message;
}
}
}
vb
' This method displays the contents of selected file from the list.
Private Sub ShowContent(ByVal sender As Object, _
ByVal args As SelectionChangedEventArgs)
' Do not continue if a file is not selected.
If (FileList.SelectedIndex <> -1) Then
Try
Using store As IsolatedStorageFile = _
IsolatedStorageFile.GetUserStoreForApplication()
Dim fileName As String = FileList.SelectedItem.ToString
FileNameBox.Text = fileName
Try
Dim curFile As IsolatedStorageFileStream = _
store.OpenFile(System.IO.Path.Combine(subDirName, _
fileName), FileMode.Open, FileAccess.Read)
Dim sr As StreamReader = New StreamReader(curFile)
FileContentBox.Text = sr.ReadToEnd
sr.Close()
Catch ex As IsolatedStorageException
Alert.Text = ex.Message
End Try
End Using
Catch ex As IsolatedStorageException
Alert.Text = ex.Message
End Try
End If
End Sub
Increasing Storage Space
This QuickStart includes a button to increase the host's quota of isolated storage space. Typically, the process for increasing the quota is initiated by the application (rather than by the user) when it determines that space is low.
Increasing the quota is a 3-step process:
-
The TryIncreaseQuotaTo method is called to prompt the host to request an increase of its quota of isolated storage space on the local computer. This method must be called from an event handler.
-
The host responds by displaying a dialog box to approve or reject the quota increase.
-
The user of the application approves or rejects the increase.
To increase the space for isolated storage
-
Add the following method to the Page class.
cs
// This method starts the process to increase the
// host's quota of storage space on the local computer.
private void OnClickIncreaseQuota(object sender, RoutedEventArgs args)
{
// Obtain an isolated store for an application.
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
// Request 5MB more space in bytes.
Int64 spaceToAdd = 5242880;
Int64 curAvail = store.AvailableFreeSpace;
// If available space is less than
// what is requested, try to increase.
if (curAvail < spaceToAdd)
{
// Request more quota space.
if (!store.TryIncreaseQuotaTo(store.Quota + spaceToAdd))
{
Alert.Text = "Increase rejected.";
}
else
{
Alert.Text = "Increase approved.";
}
}
else
{
Alert.Text = "5 MB is still available.";
}
}
}
catch (IsolatedStorageException ex)
{
Alert.Text = ex.Message;
}
}
vb
' This method starts the process to increase the
' host's quota of storage space on the local computer.
Private Sub OnClickIncreaseQuota(ByVal sender As Object, _
ByVal args As RoutedEventArgs)
' Obtain an isolated store for an application.
Try
Using store As IsolatedStorageFile = _
IsolatedStorageFile.GetUserStoreForApplication()
' Request 5MB more space in bytes.
Dim spaceToAdd As Int64 = 5242880
Dim curAvail As Int64 = store.AvailableFreeSpace
' If available space is less than
' what is requested, try to increase.
If curAvail < spaceToAdd Then
' Request more quota space.
If Not store.TryIncreaseQuotaTo((store.Quota + _
spaceToAdd)) Then
Alert.Text = "Increase rejected."
Else
Alert.Text = "Increase approved."
End If
Else
Alert.Text = "5 MB is still available."
End If
End Using
Catch ex As IsolatedStorageException
Alert.Text = ex.Message
End Try
End Sub
Running the Application
To work with files
-
To create a file, specify a file name, type text for its content, and click Save File. A file is not required to have content.
-
To view and modify a file, select the file in the list and its contents will display. You can modiy its contents and click Save File.
-
If you specify a file name that is already in the list, the file in the list will be used and its content will be replaced with the new content when you click Save File.
-
To delete a file, select it in the list and click Delete File.
|