3. Coding the
Application
In Solution Explorer, open MainPage.xaml.cs and replace the code there with the following
C# code blocks, in precisely the order in which they are presented.
3.1. Specifying
the Namespaces
Begin by specifying the
namespaces the application will use. System.IO.IsolatedStorage
and System.IO contain the APIs needed
to work with the isolated file storage.
using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
namespace IsolatedStorageStoreImageDemo
{
3.2. Initializing
Variables
Now add the following
block of code to MainPage.xaml.cs to initialize the
application's variables.
public partial class MainPage : PhoneApplicationPage
{
private string ImageFileName = null;
WebClient _webClient; // Used for downloading the image first time from the web site
...
3.3. Initializing
the Application
Now add the application's
constructor, which uses the WebClient.OpenReadCompleted event to download its target image. The code
contains logic to check whether enough space is available in the phone's
isolated storage to save the downloaded image. If space is available,
the image gets saved; otherwise it's loaded directly into the image
control.
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait |
SupportedPageOrientation.Landscape;
_webClient = new WebClient();
// Handles when the image download is completed
_webClient.OpenReadCompleted += (s1, e1) =>
{
if (e1.Error == null)
{
try
{
bool isSpaceAvailable =
IsSpaceIsAvailable(e1.Result.Length);
if (isSpaceAvailable)
{
// Save Image file to Isolated Storage
using (IsolatedStorageFileStream isfs =
new IsolatedStorageFileStream(ImageFileName,
FileMode.Create,
IsolatedStorageFile.GetUserStoreForApplication()))
{
long imgLen = e1.Result.Length;
byte[] b = new byte[imgLen];
e1.Result.Read(b, 0, b.Length);
isfs.Write(b, 0, b.Length);
isfs.Flush();
}
LoadImageFromIsolatedStorage(ImageFileName);
}
else
{
BitmapImage bmpImg = new BitmapImage();
bmpImg.SetSource(e1.Result);
image1.Source = bmpImg;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
};
}
NOTE
In order to create a
sub-directory, you must create a directory path string, such as "MyDirectory1\SubDirectory1"
and pass it to the CreateDirectory method. To add a file to SubDirectory1, you must create a string that combines the
file name with its path, such as "MyDirectory1\SubDirectory1\MyFileInSubDirectory1.txt",
and then useIsolatedStorageFileStream
to create a file. In order to add contents to the file, use StreamWriter.
When you use the Remove method in IsolatedStorageFile, use it with caution as it will delete all
directories and files. To avoid accidently deleting everything in the
isolated storage, create a warning prompt window to confirm with the
user that it will be OK to delete everything in the isolated storage.
Another possibility is to use
IsolatedStorage.DeleteFileorIsolatedStorage.DeleteDirectory to delete a
specific file or directory to avoid removing all files or directories.
Please refer to MSDN documentation for more information at http://msdn.microsoft.com/en-us/library/kx3852wf(VS.85).aspx.
System.IO.Path.Combine
provides a great way to combine directory paths and files without
worrying if the backslashes "\" are
properly added. Also, when searching files or directories, you can use a
wild card "*" when building a
directory or file path.
|
|
3.4. Checking
Availability of Isolated Storage Space
Now add code for the isSpaceAvailable helper method that the application uses to
determine whether there is enough space available in isolated storage
to store the image.
// Check to make sure there are enough space available on the phone
// in order to save the image that we are downloading on to the phone
private bool IsSpaceIsAvailable(long spaceReq)
{
using (IsolatedStorageFile store =
IsolatedStorageFile.GetUserStoreForApplication())
{
long spaceAvail = store.AvailableFreeSpace;
if (spaceReq > spaceAvail)
{
return false;
}
return true;
}
}
3.5. Adding a
Button Event to Retrieve the Image from Isolated Storage
When the "Get Image" button is
clicked, we check to see if the image exists in the isolated storage.
If the image exists, the image is loaded from the isolated storage,
otherwise the image is downloaded from the web site.
private void btnGetImage_Click(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile isf =
IsolatedStorageFile.GetUserStoreForApplication())
{
bool fileExist = isf.FileExists(ImageFileName);
if (fileExist)
{
LoadImageFromIsolatedStorage(ImageFileName);
}
else
{
if (!string.IsNullOrEmpty(txtImageUrl.Text))
{
// Use Uri as image file name
Uri uri = new Uri(txtImageUrl.Text);
ImageFileName = uri.AbsolutePath;
_webClient.OpenReadAsync(new Uri(txtImageUrl.Text));
}
}
}
}
3.6. Adding a
Method to Retrieve the Image from Isolated Storage
The image is streamed
directly from the isolated storage into the image control.
private void LoadImageFromIsolatedStorage(string imageFileName)
{
// Load Image from Isolated storage
using (IsolatedStorageFile isf =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream =
isf.OpenFile(imageFileName, FileMode.Open))
{
BitmapImage bmpImg = new BitmapImage();
bmpImg.SetSource(isoStream);
image1.Source = bmpImg;
}
}
}
}
}
3.7. Testing the
Finished Application
To test the completed
application, press F5 on your keyboard and run it.
In this brief demo, you've
learned to work with isolated storage files by storing a downloaded
image into the isolated storage and then retrieving the image from the
isolated storage. In the next demo, you will learn to interact with the
name and value dictionary of the isolated storage settings.