WP8 - Storages的轉變

Windows Phone 8 – Storages的轉變

過去在WP 7.1 SDK只能使用Isolated Storage在本機儲存資料,但到了WP 8之後,增加了支援SD Card的應用,

例如:指定應用程式安裝的地點、存取SD Card中的資料;更支援Win32 Storage APIs等,讓處理的方式變得更多元。

因此,本篇文章針對幾個特別部分加以說明,並根據參考資料整理出相關在開發上要注意WP 7.1與WP 8的差異。

 

大略將新的Storage分成以下幾個項目:

(A) Installation folder;

(B) Local folder;

(C) Media library;

(D) External storage (SD Card);

(E) Win32 storage APIs supported on Windows phone 8;
圖片1

 

(A - 1) Installation Folder

     該資料夾為唯讀(Read-only),裡面包括了應用程式本身的Packages,例如:*.dll、Assets等。在過去WP 7.1時,

如果有使用過SQL CE,可以看到appdata這個關鍵字,如<Windows Phone 7 - Local Database概論 - 1>說明。

到了WP 8有了其他的方式,可以存取到該資料夾下內容,如下表:

API Description WP OS 7.1 WP OS 8
GetResourceStream(Uri) Use this method to stream files from the installation folder. 可參考<How to deploy a reference database with an app for Windows Phone> green check mark green check mark
DataContext To connect to a reference database that is part of the app package, use the installation folder protocol in the path when you create your local database object. 可參考<Local database connection strings for Windows Phone> green check mark green check mark
InstalledLocation The InstalledLocation property of the current Package class returns the installation folder as a StorageFolder object. Use the Path property to get the full path of the installation folder. red x green check mark
StorageFileStorageFolder Use these APIs to work with files and folders in the installation folder. red x green check mark

上表可以看到在新的WP 8 SDK裡支援了二個新的機制:InstallLocationStorageFile、StorageFolder,二種新的方式也支援處理

Installation Folder(安裝目錄)與Local Folder(程式空間)的檔案與目錄,非常特別,往下針對這二個部分的API加以說明。

 

以下針對WP OS所有的folder protocols加以說明:

(A - 2) Installation folder protocols

     使用appdatams-appx二個protocol來取得Installation folder的位置。雖然這二個Protocol指向到相同的位置

但是它們無法互換使用。原因來自「ms-appx:///」使用AP是Windows命名空間下的APIs;「appdata:/」使用URI

的方式支援其他的API,其二者的使用方法如下:

以要取得Installation folder下AppSetup目錄中的initialSettings1.xml檔案為例:

   1: // Reference the installation folder with the appdata protocol.
   2: Uri myInitialSettingsFileUri = 
   3:     new System.Uri("appdata:/AppSetup/initialSettings1.xml");
   4:  
   5: // Get a file from the installation folder with the ms-appx protocol.
   6: var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(
   7:                          new Uri("ms-appx:///AppSetup/initialSettings2.xml"));

需注意appdata使用「/」,而ms-appx平使用「///」來當作schema的宣告詞。另外,StorageFile使用非同步的

載入方式,但加上了await(c# 4.0)的新機制,讓讀取檔案是使用非同步的讀取方式。

 

另外,在Package.InstalledLocation | installedLocation提供一些方法去相對路徑以取得package下的檔案,

有幾個要注意的地方,如下:

利用URI相對路徑至Package root:<img src="/file.png" alt="" />;

利用ms-appx:/// protocol:<img src="ms-appx://packageFullName/file.png" alt="" />;

     =>注意上述的範例,ms-appx://只用了「//」而非「///」,因此要補上「packagefullname」;

可省略package名稱,讓系統來填寫:<img src="ms-appx:///file.png" alt="" />;

    =>使用「///」,直接省略「packagefullname」;

詳細的部分可參考<How to load file resources (Windows Store apps using JavaScript and HTML)>;

 

 

(B – 1) Local folder

     代表應用程式資料儲存區的root folder,例如:WP 7.1的Isolated Storage,Local Folder本身獨立於其他應用程式

應用程式之間無法直接存取。以下列出在WP 7.1與WP 8在local folder上的定義:

API Description WP OS 7.1 WP OS 8
DataContext Local database files are stored in the local folder. To connect to a local database, use the local folder protocol in the path when you create your local database object. green check mark green check mark
IsolatedStorageSettings Work with key/value in the local folder. green check mark green check mark
IsolatedStorageFile Work with files and folders in the local folder. green check mark green check mark
StorageFileStorageFolder Use these APIs to work with files and folders in the local folder. red x green check mark
LocalFolder The LocalFolder property of the current ApplicationData class returns the local folder as a StorageFolder object. Use the Path property to get the full path of the local folder red x green check mark

 

(B-2) Local folder protocols

     使用isostorems-appdata二種protocol來連結至local folder的path。同樣地,雖然二個protocol可以存取到local folder,

但依舊無法合著用,其原因來自「ms-appdata:///local/」使用的APIs來自Windows命名空間,而「isostore:/」則採用URI

提供其他APIs使用。如下方範例:

以要取得Local folder下的mydb.sdf與AppConfigSettings.xml檔案為例:

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

一樣要注意,使用ms-appdata時使用的是「///」做為schema分隔,而isostore使用的是「/」二都有所不同。

而且使用URI的話,在「/」之後的字數不可超過185個字;例如:isostore:/mydb.sdf,用了8個字數:mydb.sdf。

 

接著來看一下在Local folder究竟有那些特殊由OS自動產生的folders:

Path Use Notes
Shared Used to host the Media, ShellContent, and Transfers folders. This folder is created when your app is installed, but it can be deleted.
Shared/Media Album Art: Apps can use this folder to display album art in the Universal Volume Control(UVC) while playing background audio. This folder is created when your app is installed, but it can be deleted. 詳細內容可以參考Reference[0].
Shared/ShellContent Tiles: Tiles can display background images on the front and back of each Tile. Background images can be stored in the local folder, but must be located in this folder or a subfolder of it. This folder is created when your app is installed, but it can be deleted.詳細內容可以參考Reference[1].
Shared/Transfers Background file transfers: Apps can save files to the local folder in the background, even when the app is no longer running in the foreground. This folder is created when your app is installed, but it can be deleted.詳細內容可以參考Reference[2].
PlatformData Photo chooser task This folder is created when your app uses the photo chooser task.

想要瀏覽自己應用程式裡的Local folder下內容,可以透過Isolated Storage Explorer (ISETool.exe)進行操作,

可參考<How to: Use the Isolated Storage Explorer Tool>或者有設備的開發者也可以使用<touchxperience>該軟體來操作。

 

 

(C) Media Library

     為Windows Phone OS在手機裡儲存Photos、Music與Videos的地方。Media Library是一個Visual Storage Container

因此,這些media由系統識別要儲存在在internal storage或是external storage(SD Card)裡,程式開發中是完全不知道的

那麼要怎麼存取裡面的資料呢?主要透過Microsoft.Xna.Framework.Media.MediaLibrary的APIs去連結Media Library取得檔案,

這個API在WP 7.1與WP 8均適用,但在WP8還有其他API可以延伸使用Media Library裡的內容,透過<>來加以說明。

以下針對Media Library APIs的部分說明WP 7.1與WP 8的差異:

Media Library API Description WP OS 7.1 WP OS 8
AlbumsArtistsSongs Read-only music access. green check mark green check mark
PicturesRootPictureAlbumSavePictures Ready-only photos access. green check mark green check mark
SavePicture、SavePictureToCameraRoll Add photos to the Saved Pictures and Camera Roll folders. green check mark green check mark
SaveSong(MediaLibrary, Uri, SongMetadata, SaveSongOperation)、
Delete(MeidaLibrary, Song)
Adds and deletes songs from the media library. red x green check mark
GetPath(Picture) Gets a file path to a photo from the specified Microsofot.Xna.Framework.Media.Picture物件 red x green check mark

在過去WP 7.1需要額外參考MediaLibrary,但到了WP8就內嵌直接參考了。

 

 

(D) External storage (SD Card)

       在WP 8開始支援存取SD Card的內容,可直接連接SD Card僅支援唯讀的功能,並且限於註冊自己的應用程式指定的檔案類型

這個部分與<>有相關。以下列出可以存取SD Card資料的API:

API Description WP OS 7.1 WP OS 8
ExternalStorageDevice Represents an SD Card. Use ExternalStorageID property to uniquely identify a card. red x green check mark
GetExternalStorageDevicesAsync Returns a collection of SD cards that are inserted in the phone. This collection will contain no more than one SD card. red x green check mark
ExternalStorageFolder Represents a folder on the SD card. Use the Path property to access the folder later. red x green check mark
ExternalStorageFile Represents a file on the SD card. Use the Path property to access the file later. red x green check mark
GetFileAsync(string)GetFolderAysnc(string) Obtain a file or folder directly from the external storage device object. red x green check mark

如果應用程式裡需要存取SD Card,需要在WMAppManifest.xml的<Capability />增加「ID_CAP_REMOVABLE_STORAGE」的宣告,

詳細的內容可參考<App manifest file for Windows Phone>。       

 

 

(E) Win32 storage APIs supported on Windows phone 8

       到了WP8開始由於採用NT的架構,因此也支援了Win32 storage APIs來處理local folder,大略如下:

API Description
CopyFile2 Copies an existing file to a new file, notifying the application of its progress through a callback function.
CreateDirectoryW Creates a new directory. If the underlying file system supports security on files and directories, the function applies a specified security descriptor to the new directory.
CreateFile2 Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. The function returns a handle that can be used to access the file or device for various types of I/O depending on the file or device and the flags and attributes specified.
DeleteFileW Deletes an existing file.
FindClose Closes a file search handle opened by the FindFirstFile, FindFirstFileEx, FindFirstFileNameW, FindFirstFileNameTransactedW, FindFirstFileTransacted, FindFirstStreamTransactedW, or FindFirstStreamW functions.
FindFirstFileExW Searches a directory for a file or subdirectory with a name and attributes that match those specified.
FindNextFileW Continues a file search from a previous call to the FindFirstFile, FindFirstFileEx, or FindFirstFileTransacted functions.
FlushFileBuffers Flushes the buffers of a specified file and causes all buffered data to be written to a file.
GetDiskFreeSpaceExW Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread.
GetFileAttributesExW Retrieves attributes for a specified file or directory.
GetFileInformationByHandleEx Flushes the buffers of a specified file and causes all buffered data to be written to a file.
GetOverlappedResultEx Retrieves the results of an overlapped operation on the specified file, named pipe, or communications device within the specified time-out interval. The calling thread can perform an alertable wait.
LockFileEx Locks the specified file for exclusive access by the calling process. This function can operate either synchronously or asynchronously and can request either an exclusive or a shared lock.
MoveFileExW Moves an existing file or directory, including its children, with various move options.
ReadFile Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if supported by the device. This function is designed for both synchronous and asynchronous operations. For a similar function designed solely for asynchronous operation, see ReadFileEx.
RemoveDirectoryW Deletes an existing empty directory.
SetEndOfFile Sets the physical file size for the specified file to the current position of the file pointer. The physical file size is also referred to as the end of the file. The SetEndOfFile function can be used to truncate or extend a file. To set the logical end of a file, use the SetFileValidData function.
SetFileAttributesW Sets the attributes for a file or directory.
SetFileInformationByHandle Sets the file information for the specified file. To retrieve file information using a file handle, see GetFileInformationByHandle or GetFileInformationByHandleEx.
SetFilePointerEx Moves the file pointer of the specified file.
UnlockFileEx Unlocks a region in the specified file. This function can operate either synchronously or asynchronously.
WriteFile Writes data to the specified file or input/output (I/O) device. This function is designed for both synchronous and asynchronous operation. For a similar function designed solely for asynchronous operation, see WriteFileEx.

更多詳細的可參考<Supported Win32 APIs for Windows Phone 8>。

 

以上是說明在WP 8與WP 7.1對於Storage存取的部分的變化,希望有助於整理出有那些APIs與Protocol的使用方式。

======

上述說明之後,了解WP8 SDK裡對於Storage的處理增加了更通用的appdata, isostore與ms-appx, ms-appdata Protocol來提供連結

Installed Folder與Local Folder的能力。除此之外還有支搜Win32 APIs與External Storage的存取機制,讓操作Storage的功能更加豐

富,雖然在WP 7.1 SDK裡沒有支援新的APIs,但在開發WP 8時仍可以使用WP 7.1的技術來操作算是相容度很高的。

希望這樣的整理對大家有所幫助,關於詳細WP8操作Storage的部分,請參考<Windows Phone 8 - 練習操作Storages>。

 

References:

[0]. How to integrate with the Music and Videos Hub for Windows Phone.

[1]. Tiles Overview for Windows Phone

[2]. How to: Implement Background File Transfers for Windows Phone

Supported Win32 APIs for Windows Phone 8

‧Auto-launching apps with file and URI associations for Windows Phone 8

Data for Windows Phone (必讀)

How to deploy a reference database with an app for Windows Phone

Local database connection strings for Windows Phone

How to load file resources (Windows Store apps using JavaScript and HTML)

Media for Windows Phone

Reading from the SD card on Windows Phone 8

 

Dotblogs Tags: