Isolated Storage to Save and Read Text File From Windows Phone 7


Introduction

In this article we are going to explore how to save and read a text file from isolated storage. Further in details we have to save the text file to the isolated storage through Windows Phone 7 and later we will read that file from isolated storage from Windows Phone 7. In this article we will also learn how to save the text file inside the directory or in a folder and after saving it into isolated storage we will retrieve that text file which is inside the directory to the Windows Phone TextBlock.

Now to accomplish that we will use the IsolatedStorageFile class to create a virtual space used to store that text file and IsolatedStorageFileStream class is used to do operations related to save, read, open, create the text file and another class named as StreamWriter to write that text to the text file and the class named as StreamReader to read the text from the text file which is stored inside the isolated storage. Further, to do that you have to follow the steps which is given below. In such type of storage, data is stored in compartments that are isolated by the current user and by the assembly in which the code exists. Additionally, data can be isolated by domain. Roaming profiles can be used in conjunction with isolated storage so isolated stores will travel with the user's profile.

Step 1: In this step, first of all we have to open a Windows Phone application; let us see how you will open it.

  • Go to Visual Studio 2010
  • File->New->Project
  • Select the template named as silverlight for Windows Phone
  • Select the Windows Phone application
  • Give it a name as you want.   

Step_1figure.jpg

Step_2fig.jpg

Step 2: In this step we will see that there are some important resources or namespaces you have to added to the MainPage.xaml.cs file; let us see the namespaces which are given below.

Step_2_fig.jpg

Step 3: In this step we will see the code for the first button named btnSvfile_Click which is given below.

Code:

private
void btnSvfile_Click(object sender, RoutedEventArgs e)

{

    IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
    //create new file
    using (StreamWriter SW = new StreamWriter(new IsolatedStorageFileStream("Info.txt", FileMode.Create, FileAccess.Write, ISF)))

    {

        string text = "Hi this is the text which will be written to the file and we can retrieve that later";

        SW.WriteLine(text);

        SW.Close();

        MessageBox.Show("text has been saved successfully to the file");

    }
}

 

Step 4: In this step we will see the code for the second button named btnRdfile_Click which is given below.

 

Code:

private
void btnRd_file_Click(object sender, RoutedEventArgs e)

{
    IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();

    IsolatedStorageFileStream FS = ISF.OpenFile("Info.txt", FileMode.Open, FileAccess.Read);

    using (StreamReader SR = new StreamReader(FS))

    {

        this.text.Text = SR.ReadLine();

    }
}

 

Step 5: In this step we will see the code for the third button named btnwrfile_Click which is given below.

 

Code:

 

private void btnwt_fileClick(object sender, RoutedEventArgs e)

{
    IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
    
//Open existing file

    IsolatedStorageFileStream FS = ISF.OpenFile("Info.txt", FileMode.Open, FileAccess.Write);

    using (StreamWriter SW = new StreamWriter(FS))

    {

        string text = "Here we have added more text about amit maheshwari which is working with MCN Solutions pvt ltd !";

        SW.Write(text);

        SW.Close();
    }
}

 

Step 6: In this step we will see the code for the fourth button named btnwt_Directory_Click which is given below.

 

Code:

 

private void btnwt_Directory_Click(object sender, RoutedEventArgs e)

{
    
//By using it we will obtain the virtual store for application

    IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
    
//Now we have to create a new folder and call it "MyFolder"

    ISF.CreateDirectory("MyFolder");
    
//Here we will Create a new file and assign a StreamWriter to the store and this new file (Info1.txt)

    //In this Also take the text contents from the text control and write it to Info1.txt

    StreamWriter SW = new StreamWriter(new IsolatedStorageFileStream("MyFolder\\Info1.txt", FileMode.OpenOrCreate, ISF));

    string text = "Hi this is the text which will be written to the file and which is in the IsolatedStorage!";

    SW.WriteLine(text);

    SW.Close();

    MessageBox.Show("Text written to the directory successfully");
}

 

Step 7: In this step we will see the code for the fifth button named btnRd_Directory_Click which is given below.

 

Code:

 

private void btnRd_Directory_Click(object sender, RoutedEventArgs e)

{

    IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();

    IsolatedStorageFileStream FS = ISF.OpenFile("MyFolder\\Info1.txt", FileMode.Open, FileAccess.Read);

    using (StreamReader SR = new StreamReader(FS))

    {

        this.text1.Text = SR.ReadLine();
    }
}

 

Step 8: In this step we will see the complete code for the MainPage.Xaml.cs file which is given below.

 

Code:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using Microsoft.Phone.Controls;

using System.IO.IsolatedStorage;

using System.IO;
namespace mytextfile

{
    public partial class MainPage :
PhoneApplicationPage

    {

        // Constructor

        public MainPage()

        {

            InitializeComponent();

        }

        private void btnwt_fileClick(object sender, RoutedEventArgs e)

        {
            IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
           
//Open existing file

            IsolatedStorageFileStream FS = ISF.OpenFile("Info.txt", FileMode.Open, FileAccess.Write);

            using (StreamWriter SW = new StreamWriter(FS))

            {

                string text = "Here we have added more text about amit maheshwari which is working with MCN Solutions pvt ltd !";

                SW.Write(text);

                SW.Close();
            }
        }
        private void btnSvfile_Click(object sender, RoutedEventArgs e)

        {
            IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
            //create new file
            using (StreamWriter SW = new StreamWriter(new IsolatedStorageFileStream("Info.txt", FileMode.Create, FileAccess.Write, ISF)))

            {

                string text = "Hi this is the text which will be written to the file and we can retrieve that later";

                SW.WriteLine(text);

                SW.Close();

                MessageBox.Show("text has been saved successfully to the file");
            }

        }
        private void btnRd_file_Click(object sender, RoutedEventArgs e)

        {

            IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();

            IsolatedStorageFileStream FS = ISF.OpenFile("Info.txt", FileMode.Open, FileAccess.Read);

            using (StreamReader SR = new StreamReader(FS))

            {

                this.text.Text = SR.ReadLine();
            }
        }
        private void btnwt_Directory_Click(object sender, RoutedEventArgs e)

        {

            //By using it we will obtain the virtual store for application

            IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
           
//Now we have to create a new folder and call it "MyFolder"

            ISF.CreateDirectory("MyFolder");
           
//Here we will Create a new file and assign a StreamWriter to the store and this new file (Info1.txt)

            //In this Also take the text contents from the text control and write it to Info1.txt

            StreamWriter SW = new StreamWriter(new IsolatedStorageFileStream("MyFolder\\Info1.txt", FileMode.OpenOrCreate, ISF));

            string text = "Hi this is the text which will be written to the file and which is in the IsolatedStorage!";

            SW.WriteLine(text);

            SW.Close();

            MessageBox.Show("Text written to the directory successfully");
        }
        private void btnRd_Directory_Click(object sender, RoutedEventArgs e)

        {

            IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();

            IsolatedStorageFileStream FS = ISF.OpenFile("MyFolder\\Info1.txt", FileMode.Open, FileAccess.Read);

            using (StreamReader SR = new StreamReader(FS))

            {

                this.text1.Text = SR.ReadLine();

            }

        }

    }

}

 

Step 9: In this step we will see the code for the MainPage.Xaml file which is given below.

 

Code:

 

<phone:PhoneApplicationPage

    x:Class="mytextfile.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"

    FontFamily="{StaticResource PhoneFontFamilyNormal}"

    FontSize="{StaticResource PhoneFontSizeNormal}"

    Foreground="{StaticResource PhoneForegroundBrush}"

    SupportedOrientations="Portrait" Orientation="Portrait"

    shell:SystemTray.IsVisible="True">
    <!--LayoutRoot is the root grid where all page content is placed-->

    <Grid x:Name="LayoutRoot" Background="Transparent">

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="*"/>

        </Grid.RowDefinitions>
        <!--TitlePanel contains the name of the application and page title-->

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

            <TextBlock x:Name="PageTitle" Text="My text file" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"

                      FontFamily="Comic Sans MS" OpacityMask="{x:Null}">

                     <TextBlock.Foreground><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="Black" Offset="0" />

                 <GradientStop Color="#FFFFFF54" Offset="1" /></LinearGradientBrush></TextBlock.Foreground>

            </TextBlock>

        </StackPanel>
        <!--ContentPanel - place additional content here-->
        <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel.Background>
                <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                    <GradientStop Color="Black" Offset="0" />
                    <GradientStop Color="#BC8BFFFF" Offset="1" />
                </LinearGradientBrush>
            </StackPanel.Background>
            <Button Content="Click to Save Text File" Click="btnSvfile_Click" Height="96" Width="430" FontFamily="Comic Sans MS" FontSize="28" Foreground="#FF30FF0D" />
            <Button Content="Click to Read Text File" Click="btnRd_file_Click" Height="89" Width="432" FontSize="28" FontFamily="Comic Sans MS">
                <Button.Foreground>
                    <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                        <GradientStop Color="Black" Offset="0" />
                        <GradientStop Color="Blue" Offset="1" />
                    </LinearGradientBrush>
                </Button.Foreground>
            </Button>
            <Button Content="Click to Write to Text File" Click="btnwt_fileClick" Height="103" Width="430" FontSize="28" FontFamily="Comic Sans MS" BorderBrush="#FFFCF2F2">
                <Button.Foreground>
                    <RadialGradientBrush>
                        <GradientStop Color="Black" Offset="0" />
                        <GradientStop Color="#FFF50078" Offset="1" />
                    </RadialGradientBrush>
                </Button.Foreground>
            </Button>

            <TextBlock x:Name="text" TextWrapping="Wrap"/>
            <Button Content="Click toWrite Text File to a Directory" Click="btnwt_Directory_Click" Height="80" Width="456"

                    FontFamily="Comic Sans MS" FontSize="22" Foreground="#FFC6FF2C"></Button>

            <Button Content="Click to Read Text File from Directory" Click="btnRd_Directory_Click" Height="76" Width="450"

                    FontFamily="Comic Sans MS" FontSize="22" Foreground="#FFF7FF91" />

            <TextBlock x:Name="text1"/>

        </StackPanel>

    </Grid>
</
phone:PhoneApplicationPage>

 

Step 10: In this step we will see the design page of the Windows Phone application which is given below.

 

Design.jpg

 

Step 11: In this step we are going to run the application by pressing F5 and the related output is given below.

 

Output 1: This is the default output whenever we run the application which is given in the figure below.


Out1.jpg

 

Output 2: Whenever we press the button named click to save the text file then it will show a messagebox that your text has been saved to a text file.


out2.jpg

 

Output 3: In this output when you click on the second button to read the test file then it will show you text on the screen which is given below.


out3.jpg

 

Output 4: If you want to write the text to the another one file then you have to click on the third button:


out4.jpg

 

Output 5: In this output if you want to save your text file inside a directory then you have to click on the fourth button and the output is given below.


out5.jpg

 

Output 6: In this you will see that you can read that file from the directory which is stored inside the isolated storage.


output6.jpg


Here are some others useful resources which may help you.

Save And Read Data From Isolated Storage in Windows Phone 7Multitasking or Tombstoning and Isolated Storage in Windows Phone 7Isolated Storage Explorer Tool in Window Phone 7Windows Azure Storage Client Library For Windows Phone: Part 1Using Isolated Storage to Save And Get an Image in Windows Phone 7


Similar Articles