this.Blog.Find(entry => entry.IsHelpful);
 Saturday, August 09, 2008
Isolated Storage

In my last post, I showed how to write stuff out to a temporary directory.  After I wrote the post, I started thinking about how people could misconstrue the meaning of it.  The post was intended to show how to dump stuff easily to a random directory on the file system.  The code that drove me to write that particular example came from a unit test that was using the temporary directory as a repository for the output of the XmlSerializer.  In other words, I really was not doing anything meaningful with the data.

To clear things up, I thought I would write a post that showed how use a unknown storage directory as a meaningful repository for application data.  What constitutes meaningful data?  I don't know, it's your app!!!  But common possibilities include application settings, user-specific data, etc...  I'm thinking of things that might be otherwise be stored in the registry.  Yeah, don't do that anymore.  I don't know about you, but the just the word "registry" causes me to shudder.

.Net has introduced a new concept called "Isolated Storage" to hold this type of information.  Isolated storage is an unspecified location on the file system that is hidden away from the application.  Even though the location is unknown, the application is guaranteed to have full permissions to it, even if it is running in a restricted security mode.  As it name implies, the location is "isolated" so that any data written to it does not affect other applications or anything else on the file system.  So as far as security goes, you're limited to only hurting yourself by maliciously or ignorantly (mis)using this repository.

Here's a code sample of how you would use it to store data:

// get the location specific to this user/assembly
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly();
// create a file to write the data to 
using ( var outStream = new IsolatedStorageFileStream("foo.txt", FileMode.Create, isf) ) 
{
    using ( var sw = new StreamWriter(outStream) ) 
    {
    	// write out the text
        sw.Write("Random text");
        sw.Close();
    }
}

And here is how you can retrieve it:

IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly();
// open the file
using ( var inStream = new IsolatedStorageFileStream("foo.txt", FileMode.Open, isf) ) 
{
    string[] files = isf.GetFileNames("foo.txt");
    if ( files.length > 0 )
    {
        StringBuilder sb = new StringBuilder();
        foreach ( var file in files )
        {
            using ( var sr = new StreamReader(inStream) )
            {
                sb.AppendLine(sr.ReadLine());
            }
        }
    }
}

This method is a much more "enterprise-y" way to access data in your applications.


Kick it on DotNetKicks.com
Saturday, August 09, 2008 3:45:26 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C#

Comments are closed.