Isolated Storage in Silverlight 2 Beta 2

Posted by: Suprotim Agarwal , on 7/1/2008, in Category Silverlight 2, 3, 4 and 5
Views: 37316
Abstract: Silverlight 2 allows you to store data safely and locally in a hidden folder outside the browser’s cache, via a feature called ‘Isolated Storage’. In this article, we will see how to create and read files in the isolated storage space. We will also see how to increase the default space limit for isolated storage
Isolated Storage in Silverlight 2 Beta 2
 
This article is based on a pre-release version of Silverlight 2 and is subject to change.
Silverlight 2 allows you to store data safely and locally in a hidden folder outside the browser’s cache, via a feature called ‘Isolated Storage’. Application code in Silverlight runs as partial trust and hence does not have access to the file system. However, a Silverlight application is allowed to create and access files by using the isolated storage API, for only those files that are stored in an Isolated Storage area. The isolated storage API’s are based on the FileStream API’s and are quiet similar to the File class.
In Beta 2, the Isolated Storage space has now been increased from 100KB to 1MB (default). The space can also be increased further by the user through the UI thread.
Advantages of Isolated Storage
1.    Provides client side storage space similar to cookies.
2.    Small data files such as custom settings, preferences, skins/themes, user name can easily be stored. If the storage space is increased, large files requiring graphical resources like images etc can also be stored.
3.    Since the Silverlight applications runs in a sandbox model (partially trusted applications), it does not have access to the File system. However the isolated storage provides a kind of a virtual file system, to store files on the client side.
4.    The default size in Silverlight 2 Beta 2 is 1MB. However this can be increased by the user.
5.    Isolated storage remains even if the cache is cleared. However it can be manually deleted by the user or application.
6.    Every application has its own portion of the isolated storage.
You can use isolated storage for a number of other uses as well, like for improving UX and reducing bandwidth. For example, an incomplete form draft can be saved in the isolated storage. The user can then come later and the application can retrieve the incomplete form (from the isolated storage) to be filled by the user. The coolest part is if the form was saved in Mozilla, it can be opened later in IE and the details can be retrieved. There is no need to contact the server, since the form was saved in the Isolated Storage. This would save the user time and efforts, and save on the bandwidth.
How to Read and Write files in the Isolated Storage?
The IsolatedStorageFileStream class provides methods to access files in the Isolated Storage and perform operations on them. In the code shown below, the IsolatedStorage class is used to open the Isolated Storage area for this Silverlight application. As already mentioned, every Silverlight application has its own portion of the isolated storage area.
To open the storage space, we call the static method GetUserStoreForApplication() on the IsolatedStorageFile class. The GetUserStoreForApplication() obtains user-scoped isolated storage. Once we get the storage, we then use the IsolatedStorageFileStream class to read and write contents in the Isolated Storage. In our example, we are storing the contents in a file called ‘MyOwnFile.txt’.
Create a file in the Isolated Storage
C#
        private void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            using (IsolatedStorageFile store =
           IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream strm =
                    new IsolatedStorageFileStream("MyOwnFile.txt",
                         FileMode.Create, store))
                {
                    using (StreamWriter sw = new StreamWriter(strm))
                    {
                        sw.Write("You can write some text over here");
                    }
                }
            }
        }
VB.NET
            Private Sub btnCreate_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
                  Using store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
                        Using strm As IsolatedStorageFileStream = New IsolatedStorageFileStream("MyOwnFile.txt", FileMode.Create, store)
                              Using sw As StreamWriter = New StreamWriter(strm)
                                    sw.Write("You can write some text over here")
                              End Using
                        End Using
                  End Using
            End Sub
If you are interested in knowing the location of the Isolated Storage space, then on my Vista box, the file gets created in:
C:\Users\Administrator.suprotim\AppData\LocalLow\Microsoft\
Silverlight\is
On a XP box, the location would be:
C:\Documents and Settings\<>\Local Settings\Application Data\Microsoft\Silverlight\is
 
Read from a file kept in the Isolated Storage
C#
        private void btnRead_Click(object sender, RoutedEventArgs e)
        {
            using (IsolatedStorageFile store =
           IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fs =
                    new IsolatedStorageFileStream("MyOwnFile.txt",
                         FileMode.Open, store))
                {
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        String txt = sr.ReadLine();
                        // Display the contents in a textblock
                        txtRead.Text = txt;
                    }
                }
            }
        }
VB.NET
            Private Sub btnRead_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
                  Using store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
                        Using fs As IsolatedStorageFileStream = New IsolatedStorageFileStream("MyOwnFile.txt", FileMode.Open, store)
                              Using sr As StreamReader = New StreamReader(fs)
                                    Dim txt As String = sr.ReadLine()
                                    ' Display the contents in a textblock
                                    txtRead.Text = txt
                              End Using
                        End Using
                  End Using
            End Sub
How to increase the Isolated Storage space?
If you want to request the user to increase the storage space, you can use the following code to request an increase by 3 MB.
C#
        private void btnIncrease_Click(object sender, RoutedEventArgs e)
        {
            IsolatedStorageFile storage = null;
            try
            {
                storage = IsolatedStorageFile.GetUserStoreForApplication();
                Int64 availSpace = storage.AvailableFreeSpace;
                Int64 incSpace = 3145728; // 1024 * 1024 * 3 = 3 MB
                if (availSpace < incSpace)
                {
                    // increase space by 3 MB
                    bool b = storage.IncreaseQuotaTo(incSpace);
                    if (b)
                    {
                        // User approved increase. Perform your actions
                    }
                    else
                    {
                        // User has rejected. You have only 1MB of space
                    }
                }
            }
            catch (IsolatedStorageException ise)
            {
 
            }
            finally
            {
                storage.Dispose();
            }
 
        }
VB.NET
            Private Sub btnIncrease_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
                  Dim storage As IsolatedStorageFile = Nothing
                  Try
                        storage = IsolatedStorageFile.GetUserStoreForApplication()
                        Dim availSpace As Int64 = storage.AvailableFreeSpace
                        Dim incSpace As Int64 = 3145728 ' 1024 * 1024 * 3 = 3 MB
                        If availSpace < incSpace Then
                              ' increase space by 3 MB
                              Dim b As Boolean = storage.IncreaseQuotaTo(incSpace)
                              If b Then
                                    ' User approved increase. Perform your actions
                              Else
                                    ' User has rejected. You have only 1MB of space
                              End If
                        End If
                  Catch ise As IsolatedStorageException
 
                  Finally
                        storage.Dispose()
                  End Try
 
            End Sub
When the code is run, the site will prompt the user for approval to utilize more space on their machines. The prompt displays the current storage space being used and the space, the application is requesting to be increased.
How to reduce the Isolated Storage space?
You cannot do that in Beta 2. At least I could not find a way of reduce the space. In fact even calling the Remove() function on the storage did not do much good. I hope this feature will be available in the final release. If anyone knows of a way that works in Beta 2, I would be eager to know about it.
Wrapping it up
The XAML file for the above code demonstrations will look similar to the following:
<UserControl xmlns:my1="clr-namespace:System.Windows.Controls.Primitives;
assembly=System.Windows.Controls.Extended"  xmlns:my="clr-namespace:System.Windows.Controls;
assembly=System.Windows.Controls.Extended"  x:Class="IsolatedStorage.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Canvas x:Name="LayoutRoot" Background="White">
        <Button x:Name="btnIncrease" Content="Increase space" Click="btnIncrease_Click" Width="90"/>
        <Button x:Name="btnCreate" Content="Create file" Click="btnCreate_Click" Canvas.Left="100" Width="70"></Button>
        <Button x:Name="btnRead" Content="Read file" Click="btnRead_Click" Canvas.Left="180" Width="70"></Button>
        <TextBlock x:Name="txtRead" Width="100" Canvas.Top="40"></TextBlock>   
    </Canvas>
</UserControl>
Just before wrapping up this article, I wanted to tell you that one of the places where you could invoke the code to store user specific information, before the application exits, is in the Application.Exit event. The next time the user runs your application; this information will be available to the user.
I hope you got a fair idea of what the Isolated Storage space is all about and how to use it. People who have worked on the .NET Framework would be already familiar with the concept of Isolated Storage. The concept remains the same in Silverlight. It’s just that the API’s to access the storage has been optimized to work with Silverlight. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed. 
 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim received the prestigious Microsoft MVP award for 17 consecutive years, until he resigned from the program in 2025. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Matt on Wednesday, August 20, 2008 10:35 AM
Very helpful especially to have a VB example.
$(this).siblings('.current').removeClass('current'); $(this).addClass('current'); $('.tabContent').children('.current').removeClass('current'); $('.tabContent').children().eq($(this).index()).addClass('current'); }); });