Windows Phone 7 Development : Working with Isolated Directory Storage (part 2)

2/25/2011 10:15:31 PM

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()

SupportedOrientations = SupportedPageOrientation.Portrait |

_webClient = new WebClient();
// Handles when the image download is completed
_webClient.OpenReadCompleted += (s1, e1) =>
if (e1.Error == null)
bool isSpaceAvailable =

if (isSpaceAvailable)
// Save Image file to Isolated Storage
using (IsolatedStorageFileStream isfs =
new IsolatedStorageFileStream(ImageFileName,

long imgLen = e1.Result.Length;
byte[] b = new byte[imgLen];
e1.Result.Read(b, 0, b.Length);
isfs.Write(b, 0, b.Length);

BitmapImage bmpImg = new BitmapImage();
image1.Source = bmpImg;
catch (Exception ex)


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

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 =
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 =
bool fileExist = isf.FileExists(ImageFileName);

if (fileExist)
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 =
using (IsolatedStorageFileStream isoStream =
isf.OpenFile(imageFileName, FileMode.Open))
BitmapImage bmpImg = new BitmapImage();
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.

  •  Windows Phone 7 Development : Working with Isolated Directory Storage (part 1)
  •  iPhone Application Development : Making Multivalue Choices with Pickers - Using Date Pickers (part 3)
  •  iPhone Application Development : Making Multivalue Choices with Pickers - Using Date Pickers (part 2) - Adding a Date Picker
  •  iPhone Application Development : Making Multivalue Choices with Pickers - Using Date Pickers (part 1)
  •  iPhone Application Development : Making Multivalue Choices with Pickers - Understanding Pickers
  •  Sync Your iPad with iTunes : Troubleshooting iTunes and the Sync
  •  Sync Your iPad with iTunes : Manually Transferring Music, Movies, Podcasts, and More on Your iPad (Drag-and-Drop Method)
  •  Windows Phone 7 Development : Internationalization - Using Resource Files to Localize Content
  •  Windows Phone 7 Development : Internationalization - Storing and Retrieving Current Culture Settings
  •  Mobile Application Security : WebOS Security - Development and Security Testing
  •  Mobile Application Security : WebOS Security - Introduction to the Platform
  •  iPhone Application Development : Getting the User’s Attention - Using Alert Sounds and Vibrations
  •  iPhone Application Development : Getting the User’s Attention - Using Action Sheets
  •  jQuery 1.3 : Modifying table appearance (part 4) - Filtering
  •  jQuery 1.3 : Modifying table appearance (part 3) - Collapsing and expanding sections
  •  jQuery 1.3 : Modifying table appearance (part 2) - Tooltips
  •  jQuery 1.3 : Modifying table appearance (part 1) - Row highlighting
  •  Windows Phone 7 Development : Using Culture Settings with ToString to Display Dates, Times, and Text
  •  Mobile Application Security : SymbianOS Security - Persistent Data Storage
  •  Mobile Application Security : SymbianOS Security - Interprocess Communication
    Top 10
    ASP.NET AJAX Extensions : Selective Page Updates with Partial Rendering
    Managing Remote in Vista
    Visual Design of Workflows with WCF and WF 4
    Windows Server 2008 R2 monitoring and troubleshooting : Event Viewer - Configuring event-based tasks & Setting up event log forwarding
    Securing SharePoint Sites with Forefront TMG 2010 (part 2) - Creating a SharePoint Publishing Rule Using Forefront TMG
    Freeware: Ubuntu, Serif WebPlus, Sony Vegas Movies
    Deploying the Client for Microsoft Exchange Server 2010 : Installing the Outlook Client for Exchange Server
    SharePoint 2010 : Workflow Modeling and Development Tools (part 1) - Microsoft Visio 2010 & SharePoint Designer 2010
    Managing Offline Files in Vista
    Upgrading to Windows Server 2003 : Architectural Changes Since Windows NT 4.0
    Most View
    Creating Link-Worthy Content and Link Marketing : Further Refining How Search Engines Judge Links
    Biggest tips guide ever! (Part 8)
    Exchange Server 2010 : Operating Without Traditional Point-in-Time Backups
    SharePoint 2010 : Upgrading an Existing Extranet Solution from SharePoint 2007
    Windows 7 : Managing the BCD Data Store
    Mobile Application Security : SymbianOS Security - Permissions and User Controls
    Cars 2.0 : Hacking by hi-fi & Playing catch-up
    Windows 7 : Configuring Disks and Drives (part 2) - Converting a Basic Disk to a Dynamic Disk
    LCD NEC EX201W
    Embedding Media Content into the web page
    Adding the Android CSS
    Windows Server 2008: Defining Organizational Units in AD DS
    Sharepoint 2010 : Virtual Machine Management with System Center Virtual Machine Manager
    Where Windows Malware Hides
    Exchange Server 2007: Manage Recipients - Configure Expansion Servers
    Windows Phone 7 Development : Working with Isolated Directory Storage (part 1)
    Installing Networking Components in Vista
    Windows Phone 7 Development : Push Notifications - Implementing Toast Notifications
    Windows 7 : Understanding User Account Control and Its Impact on Performance
    .NET security : Isolated Storage Explained