Analysis of isolated storage mechanism in Windows Phone 8

Analysis of isolated storage mechanism in Windows Phone 8

【51CTO translation】The role of the isolated storage mechanism is to implement local data storage for the Windows Phone system. The reason why it is called "isolated" is that other applications will not be able to access the current specific data. In today's article, we will learn about the concept of isolated storage and learn how to use it to store data in Winodws Phone 8 in a more secure way.

The mobile architecture used by isolated storage is similar to Silverlight-based applications on the Windows platform. All I/O operations are confined to the scope of isolated storage, and there is no direct access to the underlying OS file system - this prevents unauthenticated access and data corruption from other applications, thus providing real security. If you want to share data between the two applications, you need some cloud service that supports data sharing as a transit platform.

Here are a few things worth mentioning about isolated storage: The local folder is the root folder used by application data storage in our mobile devices. We can implement local data storage in two ways. The first is through a name/value pair collection called IsolatedStorageSettings. The second way is to use IsolatedStorageFile to create actual files and folders. Let's take a look at several important contents that need to be paid close attention to in the isolated storage mechanism:

  • An isolated storage usage permission allocation mechanism that sets storage limits through IsolatedStoragePermission objects.
  • If data needs to be written outside the allocation mechanism, you need to add an exception through IsolatedStorageException.
  • IsolatedStorageFilePermission is responsible for deciding whether to provide permissions for a specified file or directory.

1. URI Scheme

When dealing with local folders in the path, we need to use the isostore or ms-appdata URI schemes. These two URI schemes allow you to access local folders, but they are not interchangeable. The role of ms-appdata is to deal with local folder roots through the API, while isostore is responsible for dealing with local folder roots. The following example can well demonstrate the difference between the two.

  1. // Create a local database in the local folder with the isostore URI scheme.  
  2.  
  3. MyDataContext db = new MyDataContext( "isostore:/mydb.sdf" );
  4.  
  5. // Get a file from the local folder with the ms-appdata URI scheme.  
  6.  
  7. var file = await Windows.StorageFile.GetFileFromApplicationUriAsync( new Uri( "ms-appdata:///local/AppConfigSettings.xml" ));

ms-appdata requires three slash characters (///) while isostore requires only one slash character (/). The total length of the path for both URI schemes cannot exceed 185 characters.

2. IsolatedStorageSettings

The simplest way to add data to isolated storage is to use the IsolatedStorageSettings class, which stores data in isolated storage as key-value pairs in the Dictionary<TKey, TValue> format. IsolatedStorageSettings is often used to store settings such as the number of images displayed per page and page layout options. Data stored in IsolatedStorageSettings will remain available during the application startup cycle.

If you just want to save the settings in the form of Username = "Fred", you can also use the ApplicationSettings object in the isolated storage. It is used in exactly the same way as when dealing with directories. The saveString method can be used to save a string value message for the key name.

  1. void saveString( string message, string name)
  2. {
  3. IsolatedStorageSettings.ApplicationSettings[name] = message;
  4.  
  5. IsolatedStorageSettings.ApplicationSettings.Save();
  6. }

This storage method is basically similar to the directory, but don't forget to call Save after adding the key.

To retrieve a value from a setting, you can use the loadString method which takes the saved setting key as a parameter and returns the value if the key exists.

  1. string loadString( string name)
  2. {
  3. if (IsolatedStorageSettings.ApplicationSettings.Contains(name))
  4. {
  5. return ( string )IsolatedStorageSettings.ApplicationSettings[name];
  6. }
  7. else  
  8. {
  9. return   null ;
  10. }
  11. }

Before you actually look it up, make sure the key exists. If you try to get a value from a key that doesn't exist, you'll get an exception.

One of the best practices is to create a special static class that contains all the settings of our application. This approach can easily ensure that we can access any component of the application at any time.

If you are developing a Universal Windows Application project, using IsolatedStorageSettings.ApplicationSettings will result in a syntax error. You need to replace it with Windows.Storage.ApplicationData.Current.LocalSettings.

3. IsolatedStorageFile

You can use the IsolatedStorageFile mechanism to save files on the user's device. We can perform various operations in isolated storage, such as creating folders and files, writing content to files, reading data, and removing files.

These files and folders cannot be accessed by other applications that are also installed on the user's device. The IsolatedStorageFileStream class is responsible for reading, writing, and creating files in isolated storage. This class extends FileStream, which means that you can use IsolatedStorageFileStream instances in most scenarios where FileStream instances can work, such as building StreamReader or StreamWriter.

File Writing

The following code snippet shows how to implement file writing in isolated storage. saveGameToIsolatedStorage creates a new file in isolated storage and saves the message string in it.

  1. private   void saveGameToIsolatedStorage( string message)
  2. {
  3. using (IsolatedStorageFile isf =
  4. IsolatedStorageFile.GetUserStoreForApplication())
  5. {
  6. using (IsolatedStorageFileStream rawStream = isf.CreateFile( "MyFile.store" ))
  7. {
  8. StreamWriter writer = new StreamWriter(rawStream);
  9. writer.WriteLine(message); // save the message  
  10. writer.Close();
  11. }
  12. }
  13. }

File Reading

The loadString function is responsible for reading and returning the text content contained in the file. This function uses FileExists to first check whether the target file exists in the isolated storage, and then uses the StreamReader instance to read the file.

  1. private   string loadString()
  2. {
  3. string result = null ;
  4. using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
  5. {
  6. if (isf.FileExists( "Myfile.store" )
  7. {
  8. using (IsolatedStorageFileStream rawStream = isf.OpenFile(filename,
  9. System.IO.FileMode.Open))
  10. {
  11. StreamReader reader = new StreamReader(rawStream);
  12. result = reader.ReadLine();
  13. reader.Close();
  14. }
  15. }
  16. }
  17. return result;
  18. }

The isolated storage mechanism is not available for Windows Store applications. Instead, these application data classes can be used in the Windows.Storage namespace included in the Windows Runtine API to save local data and files.

It is recommended that you dispose of IsolatedStorageFile and IsolatedStorageFileStream instances in a timely manner when they are no longer needed. The using statement can automatically complete the above tasks, so you should use it extensively as a best practice.

External file writing

To overwrite the existing contents of an external file, you can first open the file using the StreamWriter class. The FileMode.Open and FileAccess.Write parameters are responsible for opening the target file and performing write access. This allows us to overwrite the existing contents of the file with the new data.

  1. IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
  2. if (myIsolatedStorage.FileExists(filename))
  3. {
  4. using (StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.Write, myIsolatedStorage)))
  5. {
  6. string someTextData = "Learn to code using Tuts+" ;
  7. writeFile.WriteLine(someTextData);
  8. writeFile.Close();
  9. }
  10. }

Add content to an existing file

Appending data to an existing file is very similar to writing data to an existing file. The only difference is that we need to set the file mode in FileMode.Append.

  1. IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
  2. if (myIsolatedStorage.FileExists(filename))
  3. {
  4. if (myIsolatedStorage.FileExists(filename))
  5. {
  6. using (StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream(filename, FileMode.Append, FileAccess.Write, myIsolatedStorage)))
  7. {
  8. string someTextData = "Use Tuts+ to Learn Creative Skills, Shape Your Future" ;
  9. writeFile.WriteLine(someTextData);
  10. writeFile.Close();
  11. }
  12. }
  13. }

Text file deletion

To delete a text file, we first need to check whether the text file exists in the isolated storage, and then use DeleteFile to delete the file.

  1. IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
  2. if (myIsolatedStorage.FileExists(filename))
  3. {
  4. myIsolatedStorage.DeleteFile(filename);
  5. }

Here, I suggest you click here to view more sample applications to learn more about how to read, write and add other data to files.

4. Isolated Storage Resource Manager

When debugging an application, you may need to save files and folders saved in the application's isolated storage to verify that the correct files are saved in the correct location. Emulators and devices running Windows Phone 8 or lower can use Windows Phone Power Tools, a GUI-based tool that can access the contents of each application's isolated storage.

Another option is to use the Isolated Storage Explorer, or ISETool, a command-line tool that is installed with the Windows Phone SDK. You can use ISETool to list, copy, and replace files and directories in your application's local folders.

ISETool works on any type of device or emulator and is usually installed in the following locations:

Program Files(x86)\MicrosoftSDKs\WindowsPhone\v8.0\Tools\IsolatedStorageExplorerTool

Here are a few important things to note when using ISETool:

  • The application must be installed in the simulator or device.
  • The emulator or device must be unlocked, but the app does not have to be running.
  • You cannot access the isolated storage of installed apps through the Windows Phone Store.
  • You cannot use ISETool to view the saved settings information through the IsolatedStorageSettings class.

To use ISETool, you need to use the following syntax:

1

ISETool.exe <cmd[:param]> <target-device[:param]> <product-id> [<desktop-path>]

Next, let's look at other operations that can be performed using ISETool.

Copy files from isolated storage to your computer

  1. Deploy the application you want to test to the simulator or device, and then create local files and directories.
  2. Get the application ID from the ProductID attribute of the application element in the WMAppManifest.xml file.
  3. Use the command prompt to go to ISETool.exe and then run the following command to copy all the files in the application isolated storage to the computer.

1

ISETool.exe ts xd f8ce6878-0aeb-497f-bcf4-65be961d4bba c:\data\myfiles

File replacement in isolated storage

Repeat the above three steps, and then use the following command to replace the files in the application isolated storage.

1

ISETool.exe rs xd f8ce6878-0aeb-497f-bcf4-65be961d4bba “C:\Data\My Files”

If you want to know more about ISETool, you may click here to view another article I wrote specifically about the use of ISETool.

Summarize

We have two simple mechanisms to choose from in Windows Phone, namely IsolatedStorageSettings and IsolatedStorageFile. Isolated storage is a storage area that contains files and directories that cannot be accessed by other applications. Isolated storage can play an important role in many scenarios. You are also welcome to click here to download the source files related to this tutorial for reference.

Original link: Working With Isolated Storage on Windows Phone 8

Nuka-Cola Translation

<<:  The open source game server framework Firefly officially integrates GFirefly!

>>:  Android 6.0 has been exposed and will be officially released in November next year

Recommend

Tencent advertising skills and common problems!

This article shares with you some difficult probl...

Programmers need to have continuous output

I believe that all programmers need to find a goo...

Why do animals like salt but plants don’t?

"Are you a sweet or salty person?" Such...

Experience using the Chinese version of Sony Z2

I have been constantly changing devices from Noki...

5 key points to detail the user growth methodology!

Before doing product operations and promotion wit...

The “User Cultivation” Model on the Internet (I)

Have you ever thought that you are being "cu...

Beware of being "pigeoned"! Beware of the hidden dangers of domestic pigeons!

Author: Ma Ruirui Liu Wenjing Peking Union Medica...