Using IsolatedStorageFile to store data in WPF Application class events

Posted by in .NET Framework category on for Beginner level | Views : 58311 red flag
Rating: 4.5 out of 5  
 2 vote(s)

In this article I am combining and covering two basic but very handy and useful concepts which has been provided using .Net framework 4.0.


This article combines and explains two main .Net framework 4.0 concepts together.

  • How to store application and user related data using IsolatedStorageFile class found inside System.IO.IsolatedStorage namespace.
  • How to override Application.OnStartup and OnExit events in System.Windows.Application class.

Explanation :

First of all , let us first understand the concept of IsolatedStorageFile .This is a new and powerful feature for storing information related to the applications in newer version of  .Net framework. This allows application data to be written to the hard disk (in a virtual file) where sometimes this is not allowed. This provides the capability to store information/data such as application state and user preference information.

Hence, to summarize ,Isolated storage is a new data storage mechanism that allows partial-trust applications running in a security sandbox to store data in a way that is controlled by the computer’s security policy. Because file I/O operations violate Internet zone security settings, isolated storage offers XBAPs a viable option to  store pieces of data on the client which can be retrieved the next time the application is started. By default, code running on the local computer, local network, or the Internet is granted the right to use isolated storage.

How does Isolated Storage Work?

Isolated storage helps to manage the reading and writing of data to a particular storage location. As discussed earlier it is like 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.

Next we focus on the concept of Application.OnStartup and OnExit events in System.Windows.Application class. The Application object has two specific events where the capture and re-creation of state should occur. The Application.OnStartup and OnExit events occur when the application is starting up and shutting down. We can override the event handlers for the startup and exit events in order to inject our own logic that can either retrieve or capture and store the current state of the application.

This example provides an example using WPF Windows form on how application data can be saved and accessed and used with isolated storage. Data can be easily read and written using IO streams with Isolated Storage.

Code sample (steps to be followed)

  • Create a Project of windows based WPF Application and Name it ‘WpfApplicationStateManagement’ (just an example)
  • We get a project having file ‘App.xaml’ and ‘Window1.xaml’ with it.
  • Open ‘Window1.xaml’ design view and drag and drop one text box and two button controls.Rename the same as per the below design code.

<Window x:Class="WpfApplicationStateManagement.Window1"
    Title="Window1" Height="197" Width="195">
        <TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBoxValue" VerticalAlignment="Top" Width="120" />
        <Button Height="23" HorizontalAlignment="Left" Margin="10,43,0,0" Name="Save" VerticalAlignment="Top" Width="75" Click="Save_Click">Save</Button>
        <Button Height="23" HorizontalAlignment="Left" Margin="10,84,0,0" Name="Retrieve" VerticalAlignment="Top" Width="75" Click="Retrieve_Click">Retrieve</Button>

  •  Now the design of window.

Now on double clicking on ‘Save’ and ‘Retrieve’ buttons will generate  Save_Click and Retrieve_Click events which is genrated on code behind ‘Window1.xaml.cs file.

  • Write the code in these events to store and retrieve information using Application class (i.e.System.Windows.Application)

private void Save_Click(object sender, RoutedEventArgs e)
            //save the textbox value in Application property dictionary
            App.Current.Properties[0] = textBoxValue.Text.Trim();

        private void Retrieve_Click(object sender, RoutedEventArgs e)
           //Retrieve the textbox value in Application property dictionary

  • Hurray! First section of the example is done.On running the application we can see the window designed by us.

  • Now enter some text (‘Hello WPF’)  in text box and click Save button.
  • The data is stored in the Application-scope property and is ready to retrieve.
  • Clicking on Retrieve button will show the value.
  • But wait a second !!! close the application and then run again.Now clicking on Retrieve button will give ‘Object reference not set to an instance of an object.’ Error.
  • Why?? Because the text box value was store in temporary memoray storage location.
  • Now the next question is ‘How to store this data and retrieve the same when we startup the application again?
  • Her comes IsolatedStorageFile concept in picture.
  • Now open the App.xaml.cs and override the OnStartup  and OnExit functions as per the below code.Do not forget to mention below namespaces.

using System.IO.IsolatedStorage;

using System.IO;

public partial class App : System.Windows.Application

        protected override void OnExit(ExitEventArgs e)

                //First get the 'user-scoped' storage information location reference in the assembly
                IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly();
                //create a stream writer object to write content in the location
                StreamWriter srWriter = new StreamWriter(new IsolatedStorageFileStream("isotest", FileMode.Create, isolatedStorage));
                //check the Application property collection contains any values.
                if (App.Current.Properties[0] != null)
                    //wriet to the isolated storage created in the above code section.
                    srWriter.WriteLine(App.Current.Properties[0].ToString() + " : (Stored at : " + System.DateTime.Now.ToLongTimeString() + ")");


            catch (System.Security.SecurityException sx)

        protected override void OnStartup(StartupEventArgs e)
                //First get the 'user-scoped' storage information location reference in the assembly
                IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly();
                //create a stream reader object to read content from the created isolated location
                StreamReader srReader = new StreamReader(new IsolatedStorageFileStream("isotest", FileMode.OpenOrCreate, isolatedStorage));

                //Open the isolated storage
                if (srReader == null)
                    MessageBox.Show("No Data stored!");
                    while (!srReader.EndOfStream)
                        string item = srReader.ReadLine();
                //close reader
            catch (Exception ex)


  • Oops! Looks like a more complicated concept, but it is simple.

  • We are just overriding these two events and with the help of IsolatedStorageFile reference , storing Application property data supplied by the text box  inside the isolated user-scoped location reference.

  • Now Run the Application and see what happens.

  • Enter ‘Hello WPF’ and hit ‘Save’ button.

  • Close the application NOW ! (do not worry data is already stored in isolated storage area)

  • Run the application again.

  •       What did we get while loading the application?
  • The message box contains ‘Hello WPF : (Stored at : 11:07:13)’

  • This means that the data what we entered in the textbox is stored automatically by the OnExit event code .The same has been retrieved when the application starts up again. Hence , We can store user related or session data using this concept as per our requirement.


Mission accomplished!



We can store user related or session data using this concept as per our requirement.



Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: kishor kumar
Member Level: Starter
Member Status: Member
Member Since: 7/1/2010 2:49:48 AM
Country: India
kishor kumar
Having 6 pyears of exp in dot net and still counting...

Login to vote for this post.

Comments or Responses

Posted by: Abhi2434 on: 7/24/2010
This is nothing to deal with WPF I guess.

You can use IsolatedStorage classes anywhere.

Login to post response

Comment using Facebook(Author doesn't get notification)