Wriju's BLOG

.NET, Cloud and everything

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

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" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock FontSize="20" Foreground="Black" Text="{Binding Path=MSG}"></TextBlock>
                <TextBlock Foreground="Black" Text="---"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>                
</ListBox>

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()
{
    //myFile.DeleteFile(sFile);
    if (!myFile.FileExists(sFile))
    {
        IsolatedStorageFileStream dataFile = myFile.CreateFile(sFile);
        dataFile.Close();
    }

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

    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
        sw.Close();

        //Refresh the display
        LoadData();
        txtMSG.Text = "";
    }
}

Namoskar!!!