Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Framework  »  Working with Isolated Storage in .NET
 »  Home  »  Windows Development  »  Working with Isolated Storage in .NET
Working with Isolated Storage in .NET
by David Wasserman | Published  08/04/2002 | .NET Framework Windows Development | Rating:
David Wasserman

David Wasserman is a Senior Software Developer residing in Toronto, Canada. He has over 10 years industry experience in a vast array of technologies and programming languages. David has also consulted for many companies in the banking, retail and communications industries via Grand Solutions Consulting Inc, where he is Vice-President. In recent years, David's focus has been working with Microsoft technologies, including Visual Basic, VB.NET, C#, ASP, ASP .NET, SQL Server and MS Access development. David can be reached at david@grandconsult.com.

 

View all articles by David Wasserman...
Working with Isolated Storage in .NET

Article source code: isolatedstorage.zip

Introduction

Among the vast number of classes and functions provided by the Microsoft .NET Framework, exists a new and powerful feature for storing information relating to users and applications called Isolated Storage. The System.IO.IsolatedStorage namespace allows data to be written to the hard disk where sometimes this is not allowed. This provides the capability to store things such as application state and user preference information.

Both ASP.NET and Windows Form Applications can use the full capabilities of isolated storage. ASP.NET applications may use it to store personalized information which is useful for customizing a site for each user. Windows Applications traditionally place application data in Windows .INI files and Windows Registry settings but now developers can also use isolated storage.

This article provides two Windows Application examples on how information can be accessed and used with isolated storage by utilizing ADO.NET and the XML namespaces. Data can be easily read and written using IO streams with Isolated Storage.

How does Isolated Storage Work?

Isolated storage helps to manage the reading and writing of data to a particular storage location. Think of it as a sandbox type area on a hard drive that various applications can write to, including those that normally don't have authorization to do so. Applications can include anything from a website to a windows application. This encompasses all trust levels of code written under the .NET framework, from no trust to full trust.

There are two types of isolation that can be used:

  1. Isolation by user and assembly
  2. Isolation by user, domain and assembly

Both types of isolation require that the storage area be associated with a user and assembly. Only the user and assembly that created the storage have access to it.

Isolation by user and assembly: Information stored with this type of isolation can be accessed by multiple applications with appropriate levels of trust. For example an intranet site can have access to this information but an internet site cannot, by default.

Isolation by user, domain and assembly: This type of isolation has the same requirements as the first type for user and assembly, and adds application domain on top if it. With application domain (or just domain, for short), isolation becomes even more granular. Now, only the code that created the storage can have access to it, and that must be an assembly run from just one application. No other application has access to the storage. This provides an extra layer of security, which is mandatory when running code from non-trusted sources such as the internet.

Which Isolation Type to Use?

Use the user and assembly storage type when running applications from trusted sources that require sharing of information among multiple applications for that assembly. Use the user, assembly and domain type when running applications from non-trusted sources such as components downloaded from the internet. You may also employ this type of storage when the requirement is that each application has its own separate storage location.

Example 1: Creating XML files with Isolated Storage

A common usage of isolated storage is a Windows Application that stores user settings. To demonstrate how to do this I have created an XML file that stores a window's background color and size, and a textbox control's text property. Try it out for yourself by creating Visual Basic.NET Windows Application in Visual Studio.NET. The Form will contain three buttons, a TextBox control and a ColorDialog control. Add controls to the Form with the following settings:

Table 1.
TypeNameText
ButtonbtnBackColorChange Background Color
ButtonbtnSaveSave Settings
ButtonbtnDeleteDelete Settings
TextBoxtxtSampleDatasample data in here
ColorDialogcdBackground 

Click the View Code button on the Solution Explorer and add in the following statements on the first line of code:

Imports System
Imports System.IO
Imports System.IO.IsolatedStorage
Imports System.Text
Imports System.Xml

This imports the necessary namespaces that are required for this program.

Add the following lines of code in the btnBackColor's Click event:

If cdBackground.ShowDialog() = DialogResult.OK Then
    Me.BackColor = cdBackground.Color
End If

This is standard code for handling results from the ColorDialog control.

I'll first describe how to save a file with isolated storage. Later in this example I'll show how to retrieve a file that has already been stored with isolated storage. The first task, with regards to isolated storage, is to create the necessary object to work with a storage file. An IsolatedStorageFile object is created. I've chosen to use the user, domain and assembly type of isolation. I don't expect to share this storage area with other applications, so this type of isolation is sufficient for my needs. The second line of code sets the isolation type with the GetUserStoreForDomain option. If I want to use user and assembly isolation instead, I'd just replace that with GetUserStoreForAssembly.

The following code segments are placed in the btnSave Click event:

Dim isoStorage As IsolatedStorageFile
isoStorage = IsolatedStorageFile.GetUserStoreForDomain

The next line of code creates an IsolatedStorageFileStream object. The first parameter is the filename/path of the XML file to be written. The second parameter contains the FileMode with which the file is opened. In this instance, a new file will be created and overwritten if the same file already exists. Finally, the last parameter is the IsolatedStorageFile object in this case isoStorage.

Dim stmWriter As New IsolatedStorageFileStream ("UserSettingsXML.xml"_
    FileMode.CreateisoStorage

Since an XML file is being written, an XmlTextWriter object is created and associated with the stream object.

Dim writer As New XmlTextWriter(stmWriterEncoding.UTF8)

The following lines of code simply write out the XML file one line at a time:

writer.Formatting = Formatting.Indented
writer.WriteStartDocument()
writer.WriteStartElement("UserSettings")
writer.WriteStartElement("BackColor")
writer.WriteString(Me.BackColor.ToArgb.ToString)
writer.WriteEndElement()
writer.WriteStartElement("Width")
writer.WriteString(Me.Width.ToString)
writer.WriteEndElement()
writer.WriteStartElement("Height")
writer.WriteString(Me.Height)
writer.WriteEndElement()
writer.WriteStartElement("SampleData")
writer.WriteString(txtSampleData.Text)
writer.WriteEndElement()
writer.WriteEndElement()

Flushing and closing the writer object will complete writing of the XML file. It's a good practice to close the file storage and stream objects. This allows for later processing of the isolated storage file without encountering any errors.

writer.Flush()
writer.Close()

stmWriter.Close()
isoStorage.Close()

That's all there is to creating an XML file using isolated storage. But what about the next time the application is started? After the settings have been saved there needs to be a way of reading them back in. The best place for this is in the Form's Load event.

Again, as in the btnSave Click event we declare and initialize a IsolatedStorageFile object.

Dim isoStorage As IsolatedStorageFile
isoStorage = IsolatedStorageFile.GetUserStoreForDomain

The next few lines determine if an XML settings file currently exists:

Dim StoreFileNames As String()
Dim StoreFile As String
StoreFileNames = isoStorage.GetFileNames("UserSettingsXML.xml")

For Each StoreFile In StoreFileNames
    If StoreFile = "UserSettingsXML.xml" Then

If the file does exist, then processing to read the XML file into a stream reader object occurs:

        Dim stmReader As New StreamReader(New IsolatedStorageFileStream_
            "UserSettingsXML.xml"FileMode.OpenisoStorage))
        Dim xmlReader As New XmlTextReader(stmReader)

Using the xmlReader object, the file is read one line at a time comparing each node to a specific setting value. When the appropriate value is found, it is read in and properly converted to update the Form with its associated value:

        While xmlReader.Read()
            Select Case xmlReader.Name
                Case "BackColor"
                    Me.BackColor = Color.FromArgb(Integer.Parse_
                        xmlReader.ReadString))
                Case "Width"
                    Me.Width = Integer.Parse(xmlReader.ReadString)
                Case "Height"
                    Me.Height = Integer.Parse(xmlReader.ReadString)
                Case "SampleData"
                    txtSampleData.Text = xmlReader.ReadString
            End Select
        End While

Again, as in the btnSave Click event we clean up by closing the reader objects:

        xmlReader.Close()
        stmReader.Close()

Close off the file search loop and the IsolatedStorageFile object:

    End If
Next

isoStorage.Close()

Lastly, there exists another control on the Form to handle, the btnDelete button. The purpose of this button is to remove the XML settings file and restore the Form to its original condition. Four simple lines of code will do the trick. The first two we've already seen; declaring and obtaining a store object. The third line performs the actual deletion. The parameter value passed is the file to be deleted. Finally, the fourth line closes the IsolatedStorageFile object.

The following code segments are placed in the btnDelete's Click event:

Dim isoStorage As IsolatedStorageFile
isoStorage = IsolatedStorageFile.GetUserStoreForDomain
isoStorage.DeleteFile("UserSettingsXML.xml")
isoStorage.Close()

Note that if the file is not found, an exception will be raised. The code sample that accompanies this article includes exception and error handling. For the sake of brevity, this is omitted from the article discussion.

Now it's time to test the code out. Try running the program, changing the background color, the text field, and resize the Form. Then click on the Save Settings button. Close the application down and restart it. It should open up with your previously saved settings. Now try deleting the settings and closing the application down again. The next time you run it, the Form's original settings will be in place.

Example 2: Creating ADO.NET DataSets with Isolated Storage

This second example is based on the exact same concept as the first example and will function identically. The difference is this example utilizes the powerful features of ADO.NET to create the settings file, instead of raw XML as in the first example.

Create a Windows Application just the same as in Example 1. Add in the same controls, see Table 1.

Click the View Code button on the Solution Explorer and add in the following statements on the first line of code:

Imports System
Imports System.IO
Imports System.IO.IsolatedStorage

This imports the necessary namespaces that are required for this program.

Right under the definition of the class, add in the code to create class level DataSet and DataTable objects. These objects will be used throughout the code to save and retrieve the data in and out of isolated storage.

Dim dsSettings As DataSet = New DataSet("Settings")
Dim tblSettings As DataTable = dsSettings.Tables.Add("userSettings")

Add the following lines of code in the btnBackColor's Click event:

If cdBackground.ShowDialog() = DialogResult.OK Then
    Me.BackColor = cdBackground.Color
End If

This is merely standard code for handling the ColorDialog control.

In this example it makes sense to explain how the settings file is loaded first, rather than saved. This will make the ideas presented easier to grasp. This brings us to the Form's Load event. The first thing to take care of is the creation of the ADO.NET table columns that will hold the settings values.

The following code segments are placed in the Form's Load event:

tblSettings.Columns.Add("BackColor"Type.GetType("System.Int32"))
tblSettings.Columns.Add("Width"Type.GetType("System.Int32"))
tblSettings.Columns.Add("Height"Type.GetType("System.Int32"))
tblSettings.Columns.Add("SampleData"Type.GetType("System.String"))

The next thing to do is create the IsolatedStorageFile object. As seen in Example 1, these two lines of code are necessary for working with a storage file:

Dim isoStorage As IsolatedStorageFile
isoStorage = IsolatedStorageFile.GetUserStoreForDomain

The following lines of code determine if a settings file already exists. Only if the file exists, will there be an attempt to read in the user settings file:

Dim StoreFileNames As String()
Dim StoreFile As String
StoreFileNames = isoStorage.GetFileNames("UserSettingsDS.xml")

For Each StoreFile In StoreFileNames
    If StoreFile = "UserSettingsDS.xml" Then

If the storage file is found, a StreamReader is created and the user settings file is read in. An IsolatedStorageFileStream is created as a StreamReader. This file is then read into the class level DataSet declared at the top of the code. The StreamReader object is then closed.

        Dim stmReader As New StreamReader(New IsolatedStorageFileStream_
            "UserSettingsDS.xml"FileMode.OpenisoStorage))
        dsSettings.ReadXml(stmReaderXmlReadMode.ReadSchema)
        stmReader.Close()

After the DataSet is loaded, the table is read one row at a time (in this case only one row exists). As each row is read in, the file settings are used to update the Form and convert the values to their respective data types.

        Dim dr As DataRow
        For Each dr In dsSettings.Tables(0).Rows
            Me.BackColor = Color.FromArgb(Integer.Parse(dr("BackColor")))
            Me.Width = Integer.Parse(dr("Width"))
            Me.Height = Integer.Parse(dr("Height"))
            txtSampleData.Text = dr("SampleData")
        Next

Close off the file search loop and the IsolatedStorageFile object:

    End If
Next

isoStorage.Close()

Guess what the btnSave button is for? You're right, it's to save the user settings in Isolated Storage. The first task is to clear out the DataTable.

The following code segments are placed in the btnSave's Click event:

tblSettings.Clear()

Set up a new DataRow and assign the current Form settings to each column in the row. Then add this DataRow to the DataTable.

Dim drSettings As DataRow
drSettings = tblSettings.NewRow

drSettings("BackColor"= Me.BackColor.ToArgb
drSettings("Width"= Me.Width
drSettings("Height"= Me.Height
drSettings("SampleData"= txtSampleData.Text

tblSettings.Rows.Add(drSettings)

Again, we create the IsolatedStorageFile object:

Dim isoStorage As IsolatedStorageFile
isoStorage = IsolatedStorageFile.GetUserStoreForDomain

Then the actual writing of the file for isolated storage takes place. This involves creating a StreamWriter object and then saving the DataSet as an XML file:

Dim stmWriter As New StreamWriter(New IsolatedStorageFileStream_
    "UserSettingsDS.xml"FileMode.CreateisoStorage))
dsSettings.WriteXml(stmWriterXmlWriteMode.WriteSchema)

After that, it is a good practice to close up these objects:

stmWriter.Close()
isoStorage.Close()

The last thing to do is add in the code for the btnDelete button. This code is identical to the code in Example 1, with the one exception of the file name being different:

Dim isoStorage As IsolatedStorageFile
isoStorage = IsolatedStorageFile.GetUserStoreForDomain
isoStorage.DeleteFile("UserSettingsDS.xml")
isoStorage.Close()

That's all there is to it! You're now finished, and can try out the same testing as suggested for Example 1.

Conclusion

This article has provided a brief introduction on how isolated storage works in the .NET Framework. The two examples show how to use isolated storage with XML and ADO.NET namespaces. It provides an easy, convenient and consistent way of storing information on client machines, that otherwise may be difficult to do.

See article source code for complete listing of all code presented in this article.

Related devCity.NET articles:

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:3.8450704225352 out of 5
 71 people have rated this page
Article Score47994
Sponsored Links