Channels ▼
RSS

.NET

Silverlight and Local Storage


Working with File Streams

You have learned by now that there's at least one way in Silverlight to obtain a stream from a newly created, or an existing, file. The CreateFile and OpenFile methods on the IsolatedStorageFile class just serve this purpose. Silverlight supports one particular type of stream, represented with the IsolatedStorageFileStream class. Therefore, an alternative way of getting a file stream in Silverlight is just creating explicitly a new instance of the file stream class. Here's how you can proceed:

using (IsolatedStorageFile iso = 
       IsolatedStorageFile.GetUserStoreForApplication()) 
{
    IsolatedStorageFileStream stream;
    stream = new IsolatedStorageFileStream(
            TESTFILE, FileMode.OpenOrCreate, iso);
    :
}

The constructor of the IsolatedStorageFileStream class accepts the name of the file to access and a FileMode value that sheds some light on your intentions about the file. The FileMode enumeration contains the values listed in Table 2. Finally, the third parameter is the reference to the root of the virtual filesystem. Once you have got a stream to operate on the content of a file -- for reading or writing -- you have two options to proceed.

Silverlight and the Local Storage

Value

Description

Append

Opens the file and seeks to the end of the file. A write-only mode, appends any written content at the bottom of the file.

Create

Creates a new file. If the file exists already it gets overwritten.

CreateNew

Creates a new file. If the file exists already an exception is thrown.

Open

Opens the specified file. If the file does not exist an exception is thrown.

OpenOrCreate

Opens the specified file. If the file does not exist, it will be created.

Truncate

Opens the specified file and truncates its size to zero.

 

Table 2: The FileMode enumeration.

The first option entails that you use the synchronous or asynchronous API for I/O defined for streams classes. The stream class features pairs of methods like Read/Write and BeginRead/BeginWrite in addition to classic stream methods such as Flush, Close, SetLength, and Seek. Finally, a stream lists a number of properties including CanRead, CanWrite, Length, and Position.

The second option is based on the fact that you leverage a helper reader or writer class to work with the stream content. Like in the full .NET Framework, these classes are named StreamReader and StreamWriter and have nearly the same programming model. The following code snippet shows how to create a file and write some content to it using a stream writer helper class:

using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream stream; stream = new IsolatedStorageFileStream( TESTFILE, FileMode.OpenOrCreate, iso); StreamWriter writer = new StreamWriter(stream); writer.Write(DateTime.Now.ToString()); writer.Close(); stream.Close(); }

Largely similar is the code that reads content out of a stream. Here's the part that relates to the StreamReader class:

StreamReader reader = new StreamReader(stream);
content = reader.ReadToEnd();
reader.Close();

The Write method of the StreamWriter class has a number of overloads to let you write content of a bunch of types -- bytes, arrays, characters, Booleans, objects. The StreamReader class, instead, is mostly a text reader class and offers facilities to read text files.

What if you need to deal with binary content? Silverlight has in store for you also a tailor-made version of the pair BinaryReader and BinaryWriter .NET Framework classes.

Dealing with Quotas

Isolated storage in Silverlight addresses a recurring problem that also Flash developers have to deal with — the volatility of the browser. If the user clears the browser's cache, everything the application may have downloaded is gone. To some extent, isolated storage is the Silverlight's counterpart to Web cookies. Well, but cookies are just extremely small containers of data. What is the maximum size, if any, of the isolated storage for a single application?

To avoid that downloaded applications flood the local hard disk with their settings and user-specific data, a threshold has been set that indicates the maximum capacity of the user store for a given application.

By using the Quota property on the IsolatedStorageFile class, you can learn about the current quota of disk space that the current application is assigned. The AvailableFreeSpace property, instead, tells about any left space. By default, each Silverlight application is given 100 KB of disk space on the local user's machine to save its own data. 100 KB may or may not be enough for some applications. Consider that the quota is per user; so it is certainly more than enough for all those applications that use the isolated storage to save preferences and temporary data such as the draft of some input.

There might be situations, though, where the limit of 100 KB per user is too low. In these cases, the Silverlight base class library makes available a method on the IsolatedStorageFile class through which the application can ask the local user to increase the quota to a given value. The method is TryIncreaseQuotaTo.

The method accepts a long value that indicates the larger size you request and returns a Boolean value that indicates, instead, the user response to the request. Any attempt to increase the application's quota, therefore, must be explicitly approved by the user. So any call to the TryIncreaseQuotaTo method results in a dialog box being displayed to the user, as in Figure 2.

Figure 2: Increasing the disk quota for local storage requires explicit user approval.

The requested size for the quota is normalized by the Silverlight runtime so that the user is prompted to approve increases that fall in the following scale: 100 KB, 1 MB, 5 MB, 10 MB, and so on, up to unlimited. Note also that the TryIncreaseQuotaTo method can only be called from within the UI thread, typically as the result of a user interface event. This is done to ensure that no downloaded application may silently modify a key parameter such as the isolated storage quota without first notifying the user.

Summary

Isolated storage was not invented for Silverlight, but perhaps finds in Silverlight its natural environment. Isolated storage lets Silverlight applications save persistent data on the user machine thus avoiding taxing the Web server with extra space consumption and extra work. Granting Silverlight applications access to local storage doesn't mean enabling any downloaded code to explore the content of the user's filesystem.Isolated storage, in fact, provides access to a sort of virtual filesystem rooted in a hidden and user-specific physical directory. No way can a Silverlight application navigate out of that subtree. Any data persisted through ad hoc file and stream classes is totally protected from other applications. The overall size of the persisted data is subject to a quota. The default value of the quota is 100 KB. This value can be programmatically modified, but the operation cannot go unattended and an explicit user approval — clicking Yes on a dialog box — is always required.

Microsoft's Fickle APIs

A Whole New Ball Game: Aspects of Mobile Application Development

Silverlight 4 Makes it Easy to Count Logical Cores


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video