Skip to content

Isolated Storage Tips #3

July 6, 2011

It has been a while since I wrote more Isolated Storage Tips, so I am going to explain a bit more about the various useful coding implementations in Isolated Storage in terms of creating text files, writing to it, and then later reading that data and appending to it.

Here is the code: –

using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using Microsoft.Phone.Controls;

namespace WP7IsolatedStorage
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            string fileName = "mytestfile.txt";

            using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // 0. Check to see if the file exists
                if (!isoStorage.FileExists(fileName))
                {
                    // file doesn't exist...create it.
                    isoStorage.CreateFile(fileName);
                }

                // 1. As we are appending to the file, we use FileMode.Append
                using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Append, isoStorage))
                {
                    // opens the file and writes to it.
                    using (var fileStream = new StreamWriter(isoStream))
                    {
                        fileStream.WriteLine(txtText.Text);
                    }
                }

                // 2. Cannot read from a stream that you opened in FileMode.Append.
                using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, isoStorage))
                {
                    // opens the file and reads it.
                    using (var fileStream = new StreamReader(isoStream))
                    {
                        txtCurrentText.Text = fileStream.ReadToEnd();
                    }
                }
            }
        }
    }
}

In point 0, we have created an IsolatedStorage File object that creates and holds the physical location of the Isolated Storage, and we then check if a current object file exists, if it doesn’t then we can create a new one.

In point 1, once we find out the file exists, we open the file which we called the object here isoStream, and set it to FileMode.Append which we then use the StreamWriter class to write to it. It is then, the contents of txtText.Text is stored into the object isoStream, where that line is appended to the file.

In point 2, finally, we have to use the using annotation again as you cannot read whilst appending. We then set the StreamReader, and use the code fileStream.ReadToEnd() to read the whole file, and place it into the txtCurrentText textbox.

From → Uncategorized

Leave a Comment

Leave a comment