This article is about Windows Phone 7 development on the 31st day"15th day of the series.
Yesterday, we discussed the tombstone mechanism in the program so that the program can seem to run in the background. Today, let's talk about a great way to store local data on the phone. Use independent storage.
What is independent storage?
Independent storage is not a new concept. It is already in use in Silverlight 2. Essentially, this is a way to store data or files in a local file system. "Independent" is because only your program can access the data. If you have two applications and you want to share data between them, you 'd better use services similar to cloud-based services that allow you to share data. An application cannot be shared. Other applications on the device can be called or interacted.
Settings and files
You can store your data locally in two ways. The first is through the key/value pair in the database, called IsolatedStorageSettings. The second is to create a real file and directory called IsolatedStorageFile. This section briefly introduces (Provided by MSDN), I will provide an in-depth example for each method.
IsolatedStorageSettings
In many cases, this may be the only storage method you need. IsolatedStorageSettings allows you to store key/value pairs in a dictionary (note that no setting is required) and then read them out. The data is always stored, whether the application is stopped/started or shut down. It always exists unless you delete it or the user detaches your application.One thing to remember is:You cannot read it before it is added to the dictionary. In each of my examples, you will see the code that checks whether the value exists before reading the data. The following example shows how to save the User-Defined code when a user receives an email update in your program. I used a multiple-choice box to allow users to choose from, and an event that saves this value to the independent storage.
Code Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Net;
Using System. Windows;
Using System. Windows. Controls;
Using System. Windows. Documents;
Using System. Windows. Input;
Using System. Windows. Media;
Using System. Windows. Media. Animation;
Using System. Windows. Shapes;
Using Microsoft. Phone. Controls;
Using System. IO. IsolatedStorage;
Namespace Day15_IsolatedStorage
{
Public partial class MainPage: PhoneApplicationPage
{
IsolatedStorageSettings settings = IsolatedStorageSettings. ApplicationSettings;
// Constructor
Public MainPage ()
{
InitializeComponent ();
InitializeSettings ();
}
Private void InitializeSettings ()
{
If (settings. Contains ("emailFlag "))
{
EmailFlag. IsChecked = (bool) settings ["emailFlag"];
}
Else settings. Add ("emailFlag", false );
}
Private void EmailFlag_Unchecked (object sender, RoutedEventArgs e)
{
Settings ["emailFlag"] = false;
}
Private void EmailFlag_Checked (object sender, RoutedEventArgs e)
{
Settings ["emailFlag"] = true;
}
}
}
As you can see, this is very simple. Remember the following:
- If you have not created it in IsolatedStorageSettings, an exception is thrown when you read its value. Check whether you have initialized the settings, or always use the Contains method to check the settings first.
- You can save any content in the settings. In my example, I saved a Boolean value, but you can save a customer object or anything you can think.
- Remember, when you read data, You Need To forcibly convert it. You will see that I converted the data to the bool value before use. Although you saved the object, it does not save its type. Whether you can see the type depends on yourself.
- Setting a value is the same as adding it to the database. The "settings. Add ()" statement is not actually necessary. I Add it to show you the syntax.
That's all. IsolatedStorageSettings is very simple. Key/value pairs can be saved with very little code. Creating and saving files is relatively complex, but it is still very simple.
IsolatedStorageFile
Using IsolatedStorageFile is a mechanism that allows you to store real files on your device. In my example, a text file is created in a sub-directory and the content in the file is read. You can also create and delete directories, subdirectories, and files. It seems that there is a lot of code, but it is actually very simple. We create a new IsolatedStorageFile object and write it to the drive using an IsolatedStorageFileStream object. I added comments to the code so that you can see more clearly what happened. There are two event handlers, one for saving files and the other for reading:
Code Using System. IO. IsolatedStorage;
Using System. IO;
Private void SaveButton_Click (object sender, RoutedEventArgs e)
{
// Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile. GetUserStoreForApplication ();
// Create new subdirectory
FileStorage. CreateDirectory ("textFiles ");
// Create a new StreamWriter, to write the file to the specified location.
StreamWriter fileWriter = new StreamWriter (new IsolatedStorageFileStream ("textFiles \ newText.txt", FileMode. OpenOrCreate, fileStorage ));
// Write the contents of our TextBox to the file.
FileWriter. WriteLine (writeText. Text );
// Close the StreamWriter.
FileWriter. Close ();
}
Private void GetButton_Click (object sender, RoutedEventArgs e)
{
// Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile. GetUserStoreForApplication ();
// Create a new StreamReader
StreamReader fileReader = null;
Try
{
// Read the file from the specified location.
FileReader = new StreamReader (new IsolatedStorageFileStream ("textFiles \ newText.txt", FileMode. Open, fileStorage ));
// Read the contents of the file (the only line we created ).
String textFile = fileReader. ReadLine ();
// Write the contents of the file to the TextBlock on the page.
ViewText. Text = textFile;
FileReader. Close ();
}
Catch
{
// If they click the view button first, we need to handle the fact that the file hasn't been created yet.
ViewText. Text = "Need to create directory and the file first .";
}
}
This is like a fascinating magic when you leave the program. When you return, the file will be loaded again (it is still there !).
You all know. Now we have two storage mechanisms available in Windows Phone 7. IsolatedStorageSettings and IsolatedStorageFile. I would love to hear your Innovative usage of these two storage structures in your program. Leave a message!
Download Sample Code
This example integrates the code shown above into a project.
Address: http://www.jeffblankenburg.com/post/31-Days-of-Windows-Phone-7c-Day-15-Isolated-Storage.aspx