Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all articles
Browse latest Browse all 1836

Working With Isolated Storage on Windows Phone 8

$
0
0

Isolated storage is used to store local data on a Windows Phone. It is "isolated" because other applications can't access this data. In this tutorial you'll get an overview of isolated storage and learn how you can use it to store data more securely on Windows Phone 8.

The mobile architecture of isolated storage is similar to the Silverlight-based applications on Windows. All I/O operations are restricted to isolated storage and do not have direct access to the underlying OS file system, which helps to provide security and prevents unauthorized access and data corruption from other apps. If you want to share data between two applications, you will need some kind of cloud-based service that can share that data for you. 

The local folder is the root folder of your app's data store. There are two ways to store data locally. The first way is through a collection of name/value pairs called IsolatedStorageSettings. The other way is through the creation of actual files and folders called IsolatedStorageFile. Here are a few things worth mentioning about isolated storage:

1. URI Schemes

Use the isostore or ms-appdata URI scheme names when addressing the local folder in a path. Both of these URI schemes let you access the local folder, but they cannot be used interchangeably. ms-appdata is used to address the root of the local folder with APIs, while isostore is used to address the root of the local folder. The following example demonstrates this. 

// Create a local database in the local folder with the isostore URI scheme.
MyDataContext db = new MyDataContext("isostore:/mydb.sdf");

// Get a file from the local folder with the ms-appdata URI scheme.
var file = await Windows.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/AppConfigSettings.xml"));

ms-appdata requires three slashes (///) and isostore requires only one slash (/). The total length of the path for any of the two URI schemes can't exceed 185 characters.

2. IsolatedStorageSettings

The simplest way to put data into isolated storage is to use the IsolatedStorageSettings class, which is a Dictionary<TKey, TValue> that stores key-value pairs in isolated storage. IsolatedStorageSettings is typically used to save settings, such as the number of images to display per page, page layout options, and so on. The data saved in IsolatedStorageSettings persists across application launches.

If you just want to store settings information like Username = "Fred", then you can use the ApplicationSettings object in isolated storage. It is used in the same way as you would use a dictionary. The saveString method can be used to save a string value message for the key name.

void saveString(string message, string name)
{
    IsolatedStorageSettings.ApplicationSettings[name] = message;
    IsolatedStorageSettings.ApplicationSettings.Save();
}

The storage works as a dictionary but remember to call Save when you have finished adding keys.

To retrieve values from settings, you can use the loadString method that takes the key of the saved settings as a parameter and returns the value if the key exists.

string loadString(string name)
{
    if (IsolatedStorageSettings.ApplicationSettings.Contains(name))
    {
    return (string)IsolatedStorageSettings.ApplicationSettings[name];
    }
    else
    {
    return null;
}
} 

Test if the key exists before you try to find it. If you're trying to get the value for a key that doesn't exist, an exception will be thrown.

A good practice is to create a special static class, that contains your application's settings. This makes it easy to access any property in your application at any time.

If you're working on a Universal Windows app project, then using IsolatedStorageSettings.ApplicationSettings will give a syntax error. You need to replace it with Windows.Storage.ApplicationData.Current.LocalSettings.

3.IsolatedStorageFile

IsolatedStorageFile is the mechanism that you can use to store files on a user's device. You can perform various operations on the isolated storage, such as creating folders and files, writing to a file, reading data, removing files, etc.

These files and folders are not accessible to other applications installed on the user's device. The IsolatedStorageFileStream class is used to read, write, and create files in isolated storage. This class extends FileStream, which means you can use an instance of IsolatedStorageFileStream in most situations where a FileStream instance might otherwise be used, such as to construct a StreamReader or StreamWriter.

Writing To a File 

The following code snippet shows you how to write to a file in isolated storage. The saveGameToIsolatedStorage function creates a new file in isolated storage and saves the string message in it.

private void saveGameToIsolatedStorage(string message)
{
    using (IsolatedStorageFile isf =
    IsolatedStorageFile.GetUserStoreForApplication())
    {
       using (IsolatedStorageFileStream rawStream = isf.CreateFile("MyFile.store"))
    {
        StreamWriter writer = new StreamWriter(rawStream);
        writer.WriteLine(message); // save the message
        writer.Close();
    }
    }
} 

Reading From a File

The loadString function reads and returns the text contained in the file. The function uses FileExists to first check if the file exists in isolated storage. It then uses an instance of StreamReader to read the file.

private string loadString()
{
    string result = null;
    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (isf.FileExists("Myfile.store")
        {
            using (IsolatedStorageFileStream rawStream = isf.OpenFile(filename, 
            System.IO.FileMode.Open)) 
            {
                StreamReader reader = new StreamReader(rawStream);
                result = reader.ReadLine();
                reader.Close();
            }
        }
    }
    return result;
} 

Isolated storage is not available for Windows Store apps. Instead, use the application data classes in the Windows.Storage namespaces included in the Windows Runtime API to store local data and files.

It is recommended to dispose off the instances of IsolatedStorageFile and IsolatedStorageFileStream when they're no longer needed. The using statement does this automatically for you and its use is considered a good practice.

Writing to an Existing File

To overwrite the contents of an existing file, use an instance of the StreamWriter class to open the file. The parameters FileMode.Open and FileAccess.Write are passed to open the file with write access. This will overwrite the existing content with new data.

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (myIsolatedStorage.FileExists(filename))
{
    using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.Write, myIsolatedStorage)))
    {
        string someTextData = "Learn to code using Tuts+";
        writeFile.WriteLine(someTextData);
        writeFile.Close();
}
}

Appending to an Existing File

Adding data to an existing file is very similar to writing data to an existing file. The only change needed is setting the file mode to FileMode.Append.

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (myIsolatedStorage.FileExists(filename))
{
    if (myIsolatedStorage.FileExists(filename))
    {
        using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(filename, FileMode.Append, FileAccess.Write, myIsolatedStorage)))
        {
            string someTextData = "Use Tuts+ to Learn Creative Skills, Shape Your Future";
            writeFile.WriteLine(someTextData);
            writeFile.Close();
        }
    }
}

Deleting a Text File

To delete a text file, we first check if the text file exists in isolated storage and then use DeleteFile to delete the file.

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (myIsolatedStorage.FileExists(filename))
{
    myIsolatedStorage.DeleteFile(filename);
}

I encourage you to explore the sample application of this tutorial to see how to read, write, and append data to a file.

4. Isolated Storage Explorer

While debugging an application, you may need to check the files and folders saved in your app's isolated storage to verify that the correct files are being saved in the correct location. Emulators and devices running Windows Phone 8 or lower can use Windows Phone Power Tools, which is a GUI-based tool for accessing the isolated storage of apps.

Another option is using the Isolated Storage Explorer or ISETool, a command line tool installed together with the Windows Phone SDK. You can use ISETool to list, copy, and replace files and directories in your app's local folder.

ISETool can be be used with any device or emulator, and is usually installed at the following location:

Program Files(x86)\MicrosoftSDKs\WindowsPhone\v8.0\Tools\IsolatedStorageExplorerTool

Here are a few things worth noting while using ISETool:

  • The app must be installed on the emulator or device.
  • The emulator or device must be unlocked, but the app doesn't have to be running.
  • You can't access the isolated storage of apps installed from the Windows Phone Store.
  • You can't view settings stored using the IsolatedStorageSettings class using ISETool.

To use ISETool, you need to use the following syntax:

ISETool.exe <cmd[:param]> <target-device[:param]> <product-id> [<desktop-path>]

Here are a couple of things that can be done using ISETool.

Copying Files From Isolated Storage to Computer

  1. Deploy the app you want to test to the emulator or a device, and create local files and directories. 
  2. Get the app ID from the ProductID attribute of the app element in the WMAppManifest.xml file.
  3. Navigate to ISETool.exe using the command prompt, and run the following command to copy all of the files from the app's isolated storage to your computer.
ISETool.exe ts xd f8ce6878-0aeb-497f-bcf4-65be961d4bba c:\data\myfiles

Replacing Files in Isolated Storage

Repeat the previous three steps and use the following command to replace files in the app's isolated storage.

ISETool.exe rs xd f8ce6878-0aeb-497f-bcf4-65be961d4bba “C:\Data\My Files”

If you want to learn more about the ISETool, I suggest you read another article I wrote about the use of the ISETool.

Conclusion

We have two simple mechanisms available on Windows Phone, IsolatedStorageSettings and IsolatedStorageFile. Isolated storage represents a storage area containing files and directories which can't be accessed by other applications. Isolated storage is useful in many situations. Feel free to download the tutorial's source files to use as a reference.

2014-12-10T15:20:09.000Z2014-12-10T15:20:09.000ZVivek Maskara

Viewing all articles
Browse latest Browse all 1836

Trending Articles