Skip to content

Isolated Storage

by Alex Peck on July 26th, 2009


Isolated storage
is provided so that applications running with least privilege are able to store data. .NET provides isolated storage equivalents for both File and FileStream.

IsolatedStorageFile

IsolatedStorageFile provides functionality to create files and folders in isolated storage. The first step is to create a store, which can be scoped as either Assembly/Machine or Assembly/User. If you use machine scope, then all users can access the data. So, user specific data should go in user scope, application data in machine scope.

IsolatedStorageFile machineStore = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly();

Click once applications can also access an application scope.

Once you have created a store you can use instance methods to manipulate files and directories. Instance properties allow you to evaluate current and maximum size, scope, and the identities (Application, Assembly, Domain) used for scoping.

IsolatedStorageFileStream

The IsolatedStorageFileStream class derives from FileStream, see .NET streams for more details. Here is an example of writing within a directory:

using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly())
{
    userStore.CreateDirectory("testDir");
 
    using (IsolatedStorageFileStream userStream = new IsolatedStorageFileStream(@"testDir\user.set", FileMode.OpenOrCreate, userStore))
    {
        using (StreamWriter userWriter = new StreamWriter(userStream))
        {
            userWriter.WriteLine("user data");
        }
    }
}

It’s slightly annoying that there is no directory exists method, so testing this before creating a directory involves calling GetDirectoryNames then iterating over the string array it returns – I didn’t show this for brevity. Here is how to read it back:

using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly())
{
    using (IsolatedStorageFileStream userStream = new IsolatedStorageFileStream(@"testDir\user.set", FileMode.Open, userStore))
    {
        StreamReader userReader = new StreamReader(userStream);
        string data = userReader.ReadLine();
    }
}

Permissions

The IsolatedStoragePermission class defines access to isolated storage capabilities. If you use isolated storage it is best practice to add an IsolatedStoragePermission attribute.

[IsolatedStorageFilePermission(SecurityAction.Demand)]
public class Program
{ /* ... */ }
No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS