Last couple of days we discussed about Page State and Application State of Windows Phone 7 (Mango). We learnt various ways of saving state of the page or application. After reading those chapters, you might have question in your mind that how to save the state of the application before closing the application and once you comeback again, you should get them back.

 

If you are familiar in Silverlight, you should have answer to this. Yes, we can use Isolated Storage to save the state of the app and read values whenever require in future.

 

In this tutorial, we will discuss about this with a simple demo code. If you are new to Isolated Storage, you will be able to learn how to use it directly in Windows Phone. Read to know more.

 

Index - Windows Phone 7 (Mango) Tutorial

 

Application UI Design (XAML)

Let's create a project and open the MainPage.xaml file to design the UI for our application. We will add a TextBlock where we will show the name of the user which was stored in IsolatedStorage. If no data is present in the store, it will show "Guest" as the default value.

 

We will also have a TextBox where the user will be able to enter his name and click "Save" button to store the entered value. For your reference, here is the XAML code for that:

 
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <StackPanel Orientation="Vertical">
        <TextBlock FontSize="40">
            <Run Text="Welcome"/>
            <Run Text="{Binding Username, ElementName=phonePage}"/>
        </TextBlock>
        <TextBlock Text="Set new Name: " FontSize="30" Margin="10,80,0,0"/>
        <TextBox x:Name="txtUsername" />
        <Button Content="Save" Width="150" Click="Save_Click"/>
    </StackPanel>
</Grid>

 

Here is the UI of the above XAML code that we just created:

 

Design of the UI for Isolated Storage Demo

 

Build the solution and run to see the application running in your Phone Emulator. Once done, we need to create two methods to save value to isolated storage and retrieve them from there.

 

Storing Data to IsolatedStorage

Let's start with the first method implementation. We will implement the functionality to store the record in the storage file. To do this, first we need to get the user store. In the store we will create a directory named "isolatedStorageDemo" and inside that we will create an XML file named "data.xml".

 

If the directory is not present, let's create it. Check for the XML file and if it is already there, delete the file (this is only for our demo app, in real scenario you have to do specific coding based on your requirement). After that, we need to create the XML file and serialize the entered value in the file to write.

 

Find the code snippet of the same here:

 
private void StoreName(string name)
{
    // get user's store
    var storage = IsolatedStorageFile.GetUserStoreForApplication();
 
    if (storage.DirectoryExists("isolatedStorageDemo") == false)
    {
        // if directory does not exist, create it
        storage.CreateDirectory("isolatedStorageDemo");
    }
 
    if (storage.FileExists("data.xml"))
    {
        // if file already exists, delete it to reset
        storage.DeleteFile("data.xml");
    }
 
    using (var storageFile = storage.CreateFile("isolatedStorageDemo\\data.xml"))
    {
        // create the file and serialize the value
        var xmlSerializer = new XmlSerializer(typeof(string));
        xmlSerializer.Serialize(storageFile, name);
    }
}

 

Note: IsolatedStorageFile class is present inside the "System.IO.IsolatedStorage" namespace, in case you are unable to find it. By the way, you can use any type of serialization here. But in our case, we are using XML serialization.

 

Retrieve Data from IsolatedStorage

The second method will retrieve the value from the Isolated Storage. For this, we will first get the instance of the User Store and if the file is present inside the said directory, it will open the file in read only mode and deserialize the content of the file.

 

Find the code snippet of the said method here for your reference:

 
private string RetrieveName()
{
    // get the user's store
    var storage = IsolatedStorageFile.GetUserStoreForApplication();
 
    if (storage.DirectoryExists("isolatedStorageDemo") 
            && storage.FileExists("isolatedStorageDemo\\data.xml"))
    {
        // if file exists in directory, open the file to read
        using (var storageFile = 
            storage.OpenFile("isolatedStorageDemo\\data.xml", FileMode.Open))
        {
            var xmlSerializer = new XmlSerializer(typeof(string));
 
            // deserialize and return the value
            return xmlSerializer.Deserialize(storageFile).ToString();
        }
    }
 
    return "Guest"; // return default value, for the first time
}

 

If the file or directory is not present in the isolated storage, we will return a default value. In our case, we are returning "Guest" as the default value.

 

Integration of Isolated Storage

Time to integrate the code in our sample app. In the XAML we binded the property called "Username" which already present in the page code behind. Now we will modify that property a little bit to store and retrieve values. In the getter of the code, we will call RetrieveName() and in the setter we will directly call StoreName(value) which passes the value entered to the property. Here is the code:

 
public string Username
{
    get { return RetrieveName(); }
    set { StoreName(value); }
}

 

Once you done with the above steps, let's build the project and run it inside the Emulator. Once the application loaded in the screen, you will see the first page where it will show "Welcome Guest" in the first line. That means, it didn't find the directory and/or file as this is our first launch and hence no file has been stored in the isolated storage.

 

As designed, you will find the TextBox and the Button just below the welcome text. Enter your name and click "Save". As per the implementation, this will store the name to the storage.

 

Third step is to close the application. For this, we will press the "Home" button present in the device hardware. This will close the application and return you to the home screen.

 

Here is the snapshot of the application screen:

 

Isolated Storage Demo to store Data at First Run           Isolated Storage Demo to read Data on Next Run

 

Once you are in the home screen of your device, come to the installed application screen and launch the app once again. As shown in the above screenshot, you will see that, it now added the name in the welcome text that you entered in the textbox. Instead of showing "Guest", it read the value from the XML file present in the store and display it there.

 

Hope this tutorial will help you to understand it better. Now you will be able to create your own application for Windows Phone 7 and use the Isolated Storage properly. Thank you for reading the tutorial. Don't forget to share it to reach out the maximum audience.

Have a question? Or, a comment? Let's Discuss it below...

dhgate

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.