Windows Phone 7 : IsolatedStorage Save and Read Data to a File

Windows Phone 7 : IsolatedStorage Save and Read Data to a File

  • Comments 4

Windows Phone 7 apps runs in an isolated environment and often application needs store and retrieve data from files. Application can use its IsolatedStorage to store and retrieve data.

The example shows how to read from a  file and display it in ListBox and save data to the file located in its isolated storage.

We need the class to create a structure for UI data binding.

//Creating the structure to display
public class MyDataClass
    public string MSG { get; set; }

After that define the UI look,

<ListBox Background="White" x:Name="lstDisplay" Grid.Row="1" >
                <TextBlock FontSize="20" Foreground="Black" Text="{Binding Path=MSG}"></TextBlock>
                <TextBlock Foreground="Black" Text="---"></TextBlock>

We now need to initialize the IsolatedStorage for our application.

IsolatedStorageFile myFile = IsolatedStorageFile.GetUserStoreForApplication();
string sFile = "DataTest.txt";

Once done we will start reading lines form the inline text file.

public void LoadData()
    if (!myFile.FileExists(sFile))
        IsolatedStorageFileStream dataFile = myFile.CreateFile(sFile);

    //Reading and loading data
    StreamReader reader = new StreamReader(new IsolatedStorageFileStream(sFile, FileMode.Open, myFile));
    string rawData = reader.ReadToEnd();

    string[] sep = new string[] { "\r\n" }; //Splittng it with new line
    string[] arrData = rawData.Split(sep,StringSplitOptions.RemoveEmptyEntries);
    List<MyDataClass> dataList = new List<MyDataClass>();
    foreach (var d in arrData)
        dataList.Add(new MyDataClass() { MSG = d });
    //Binding data to the UI for display
    lstDisplay.ItemsSource = dataList;

Below is how we can save the data in the file.

private void btnSave_Click(object sender, RoutedEventArgs e)
    if (txtMSG.Text.Trim() !="")
        string sMSG = txtMSG.Text;
        StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream(sFile, FileMode.Append, myFile));
        sw.WriteLine(sMSG); //Wrting to the file

        //Refresh the display
        txtMSG.Text = "";


Leave a Comment
  • Please add 1 and 6 and type the answer here:
  • Post
  • thank you

  • Thanks a lot. This was what I wanted. (And have been searching for for hours.) :-)

  • Error 1 The name 'txtMSG' does not exist in the current context

    Can you explain please why is this error exist? What is missing in your code? A textbox?

    Thank you

  • txtMSG - will be a textbox so you need to add one TextBox in the xaml and x:Name="txtMSG"

Page 1 of 1 (4 items)