儲存及擷取設定和其他 app 資料Store and retrieve settings and other app data

應用程式資料 是由特定應用程式所建立及管理的可變資料。App data is mutable data that is created and managed by a specific app. 其中包含了執行階段狀態、應用程式設定、使用者喜好設定、參考內容 (如字典應用程式中的字典定義) 及其他設定。It includes runtime state, app settings, user preferences, reference content (such as the dictionary definitions in a dictionary app), and other settings. app 資料不同於 使用者資料 ,後者是使用者在使用 app 時建立和管理的資料。App data is different from user data , data that the user creates and manages when using an app. 使用者資料包括文件或媒體檔案、電子郵件或通訊記錄,或保存使用者建立之內容的資料庫記錄。User data includes document or media files, email or communication transcripts, or database records holding content created by the user. 使用者資料可能對於多個 app 都是實用或有意義的。User data may be useful or meaningful to more than one app. 使用者資料通常是使用者想要當做與應用程式本身無關之實體來操作或傳送的資料 (如文件)。Often, this is data that the user wants to manipulate or transmit as an entity independent of the app itself, such as a document.

有關此應用程式資料的重要注意事項: App 資料的生命週期與 app 生命週期息息相關。Important note about app data: The lifetime of the app data is tied to the lifetime of the app. 如果移除應用程式,所有應用程式資料也會隨之遺失。If the app is removed, all of the app data will be lost as a consequence. 請勿使用 app 資料來儲存使用者資料或使用者可能認為重要且無法取代的任何資料。Don't use app data to store user data or anything that users might perceive as valuable and irreplaceable. 建議以使用者的媒體櫃和 Microsoft OneDrive 來儲存這類資訊。We recommend that the user's libraries and Microsoft OneDrive be used to store this sort of information. app 資料適合儲存 app 特定的使用者喜好設定、各種設定值和我的最愛。App data is ideal for storing app-specific user preferences, settings, and favorites.

app 資料類型Types of app data

app 資料有兩種類型:設定和檔案。There are two types of app data: settings and files.

SettingsSettings

您可以使用設定來儲存使用者喜好設定和 app 狀態資訊。Use settings to store user preferences and application state info. 應用程式資料 API 可讓您輕鬆建立及擷取設定 (本文稍後將說明一些範例)。The app data API enables you to easily create and retrieve settings (we'll show you some examples later in this article).

以下是可用於應用程式設定的資料類型:Here are data types you can use for app settings:

  • UInt8Int16UInt16Int32UInt32Int64UInt64SingleDoubleUInt8 , Int16 , UInt16 , Int32 , UInt32 , Int64 , UInt64 , Single , Double
  • 布林值Boolean
  • Char16StringChar16 , String
  • DateTimeTimeSpanDateTime, TimeSpan
  • GUIDPointSizeRectGUID , Point, Size, Rect
  • ApplicationDataCompositeValue:一組必須個別序列化和還原序列化的相關應用程式設定。ApplicationDataCompositeValue: A set of related app settings that must be serialized and deserialized atomically. 使用複合設定,可以輕鬆管理不可部分完成的互相依存設定更新。Use composite settings to easily handle atomic updates of interdependent settings. 在並行存取和漫遊期間,系統可確保複合設定的完整性。The system ensures the integrity of composite settings during concurrent access and roaming. 複合設定是針對少量資料最佳化,如果針對大型資料集使用複合設定,可能會拖慢系統效能。Composite settings are optimized for small amounts of data, and performance can be poor if you use them for large data sets.

檔案Files

使用檔案可儲存二進位資料,或啟用您自己的自訂序列化類型。Use files to store binary data or to enable your own, customized serialized types.

將 app 資料儲存在 app 資料存放區Storing app data in the app data stores

安裝 app 時,系統會為 app 提供分別用於設定和檔案的個別使用者資料存放區。When an app is installed, the system gives it its own per-user data stores for settings and files. 您不需知道這個資料存在的位置與形式,因為系統會負責管理實體存放裝置,以確保資料會與其他 app 和其他使用者隔離。You don't need to know where or how this data exists, because the system is responsible for managing the physical storage, ensuring that the data is kept isolated from other apps and other users. 當使用者安裝您的 app 更新時,系統也會保存這些資料存放區的內容,而當使用者解除安裝您的 app 時,系統會徹底地移除這些資料存放區的內容。The system also preserves the contents of these data stores when the user installs an update to your app and removes the contents of these data stores completely and cleanly when your app is uninstalled.

每個應用程式在它的應用程式資料存放區中,都有系統定義的數個根目錄:一個給本機檔案、一個給漫遊檔案,還有一個給暫存檔案。Within its app data store, each app has system-defined root directories: one for local files, one for roaming files, and one for temporary files. 您的應用程式可在這些根目錄中新增檔案與新容器。Your app can add new files and new containers to each of these root directories.

本機應用程式資料Local app data

本機應用程式資料應該用於需要在應用程式工作階段之間保留,而且不適用應用程式資料漫遊的任何資訊。Local app data should be used for any information that needs to be preserved between app sessions and is not suitable for roaming app data. 不適用於其他裝置上的資料也應該儲存在這裡。Data that is not applicable on other devices should be stored here as well. 儲存的本機資料沒有一般大小限制。There is no general size restriction on local data stored. 對於不需漫遊的資料或大型資料集,請使用本機應用程式資料存放區。Use the local app data store for data that it does not make sense to roam and for large data sets.

擷取本機應用程式資料存放區Retrieve the local app data store

您必須先擷取本機應用程式資料存放區,才可以讀取或寫入本機應用程式資料。Before you can read or write local app data, you must retrieve the local app data store. 若要擷取本機 app 資料存放區,請使用 ApplicationData.LocalSettings 屬性取得 app 的本機設定,以做為 ApplicationDataContainer 物件。To retrieve the local app data store, use the ApplicationData.LocalSettings property to get the app's local settings as an ApplicationDataContainer object. 使用 ApplicationData.LocalFolder 屬性來取得 StorageFolder 物件中的檔案。Use the ApplicationData.LocalFolder property to get the files in a StorageFolder object. 使用 ApplicationData.LocalCacheFolder 屬性來取得本機 app 資料存放區中的資料夾,讓您可以儲存不包含在備份與還原中的檔案。Use the ApplicationData.LocalCacheFolder property to get the folder in the local app data store where you can save files that are not included in backup and restore.

Windows.Storage.ApplicationDataContainer localSettings = 
    Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = 
    Windows.Storage.ApplicationData.Current.LocalFolder;

建立及擷取簡單的本機設定Create and retrieve a simple local setting

若要建立或寫入設定,請使用 ApplicationDataContainer.Values 屬性存取上一個步驟中取得之 localSettings 容器的設定。To create or write a setting, use the ApplicationDataContainer.Values property to access the settings in the localSettings container we got in the previous step. 這個範例會建立名為 exampleSetting 的設定。This example creates a setting named exampleSetting.

// Simple setting

localSettings.Values["exampleSetting"] = "Hello Windows";

若要擷取設定,請使用您用來建立設定的相同 ApplicationDataContainer.Values 屬性。To retrieve the setting, you use the same ApplicationDataContainer.Values property that you used to create the setting. 此範例說明如何擷取我們剛建立的設定。This example shows how to retrieve the setting we just created.

// Simple setting
Object value = localSettings.Values["exampleSetting"];

建立及擷取本機複合值Create and retrieve a local composite value

若要建立或寫入複合值,請建立 ApplicationDataCompositeValue 物件。To create or write a composite value, create an ApplicationDataCompositeValue object. 這個範例會建立名為 exampleCompositeSetting 的複合設定,然後將它新增到 localSettings 容器。This example creates a composite setting named exampleCompositeSetting and adds it to the localSettings container.

// Composite setting

Windows.Storage.ApplicationDataCompositeValue composite = 
    new Windows.Storage.ApplicationDataCompositeValue();
composite["intVal"] = 1;
composite["strVal"] = "string";

localSettings.Values["exampleCompositeSetting"] = composite;

此範例說明如何擷取我們剛建立的複合值。This example shows how to retrieve the composite value we just created.

// Composite setting

Windows.Storage.ApplicationDataCompositeValue composite = 
   (Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["exampleCompositeSetting"];

if (composite == null)
{
   // No data
}
else
{
   // Access data in composite["intVal"] and composite["strVal"]
}

建立和讀取本機檔案Create and read a local file

若要在本機 app 資料存放區中建立和更新檔案,請使用檔案 API,例如 Windows.Storage.StorageFolder.CreateFileAsyncWindows.Storage.FileIO.WriteTextAsyncTo create and update a file in the local app data store, use the file APIs, such as Windows.Storage.StorageFolder.CreateFileAsync and Windows.Storage.FileIO.WriteTextAsync. 這個範例會在 localFolder 容器中建立名為 dataFile.txt 的檔案,然後在這個檔案中寫入目前的日期與時間。This example creates a file named dataFile.txt in the localFolder container and writes the current date and time to the file. 來自 CreationCollisionOption 列舉的 ReplaceExisting 值,指出檔案如果已經存在,就會取代它。The ReplaceExisting value from the CreationCollisionOption enumeration indicates to replace the file if it already exists.

async void WriteTimestamp()
{
   Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = 
       new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");

   StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt", 
       CreationCollisionOption.ReplaceExisting);
   await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTimeOffset.Now));
}

若要在本機 app 資料存放區中開啟和讀取檔案,請使用檔案 API,例如 Windows.Storage.StorageFolder.GetFileAsyncWindows.Storage.StorageFile.GetFileFromApplicationUriAsyncWindows.Storage.FileIO.ReadTextAsyncTo open and read a file in the local app data store, use the file APIs, such as Windows.Storage.StorageFolder.GetFileAsync, Windows.Storage.StorageFile.GetFileFromApplicationUriAsync, and Windows.Storage.FileIO.ReadTextAsync. 這個範例會開啟上一個步驟中建立的 dataFile.txt 檔案,然後讀取該檔案的日期。This example opens the dataFile.txt file created in the previous step and reads the date from the file. 如需從各種位置載入檔案資源的詳細資料,請參閱如何載入檔案資源For details on loading file resources from various locations, see How to load file resources.

async void ReadTimestamp()
{
   try
   {
      StorageFile sampleFile = await localFolder.GetFileAsync("dataFile.txt");
      String timestamp = await FileIO.ReadTextAsync(sampleFile);
      // Data is contained in timestamp
   }
   catch (Exception)
   {
      // Timestamp not found
   }
}

漫遊資料Roaming data

如果您在應用程式中使用漫遊資料,使用者就能夠跨多種裝置,輕鬆地讓您的應用程式資料保持同步。If you use roaming data in your app, your users can easily keep your app's app data in sync across multiple devices. 如果使用者在多個裝置上安裝應用程式,作業系統會保持應用程式資料的同步,這樣能減少使用者在第二個裝置上需進行的應用程式設定工作量。If a user installs your app on multiple devices, the OS keeps the app data in sync, reducing the amount of setup work that the user needs to do for your app on their second device. 即使在不同的裝置上,使用者也可利用漫遊資料以繼續上次未完成的工作,像是撰寫清單。Roaming also enables your users to continue a task, such as composing a list, right where they left off even on a different device. 作業系統會在更新時將漫遊資料複寫到雲端,然後將資料同步到安裝應用程式的其他裝置上。The OS replicates roaming data to the cloud when it is updated, and synchronizes the data to the other devices on which the app is installed.

作業系統會限制每個應用程式的應用程式資料漫遊大小。The OS limits the size of the app data that each app may roam. 請參閱 ApplicationData.RoamingStorageQuotaSee ApplicationData.RoamingStorageQuota. 如果應用程式到達這個限制,在應用程式的總應用程式資料漫遊再次少於這個限額之前,將不會再複寫任何應用程式資料到雲端。If the app hits this limit, none of the app's app data will be replicated to the cloud until the app's total roamed app data is less than the limit again. 基於這個原因,僅針對使用者喜好設定、連結以及小型的資料檔案使用漫遊資料是最佳做法。For this reason, it is a best practice to use roaming data only for user preferences, links, and small data files.

使用者只要透過一些裝置,就能在需要的時間間隔內存取雲端中的應用程式漫遊資料。Roaming data for an app is available in the cloud as long as it is accessed by the user from some device within the required time interval. 如果使用者執行應用程式的時間少於這個時間間隔,漫遊資料就會從雲端中移除。If the user does not run an app for longer than this time interval, its roaming data is removed from the cloud. 如果使用者解除安裝應用程式,漫遊資料會保存在雲端,而不會自動移除。If a user uninstalls an app, its roaming data isn't automatically removed from the cloud, it's preserved. 如果使用者在這段時間間隔內重新安裝 app,就會從雲端重新同步漫遊資料。If the user reinstalls the app within the time interval, the roaming data is synchronized from the cloud.

漫遊資料的可行與禁止事項Roaming data do's and don'ts

  • 為使用者喜好設定和自訂、連結和小型資料檔案使用漫遊。Use roaming for user preferences and customizations, links, and small data files. 例如,使用漫遊在使用者的所有裝置上保留背景色彩喜好設定。For example, use roaming to preserve a user's background color preference across all devices.
  • 使用漫遊功能讓使用者可以繼續在不同的裝置完成工作。Use roaming to let users continue a task across devices. 例如,漫遊草稿電子郵件的內容或閱讀應用程式中最近檢視的頁面等應用程式資料。For example, roam app data like the contents of an drafted email or the most recently viewed page in a reader app.
  • 透過更新應用程式資料的方式處理 DataChanged 事件。Handle the DataChanged event by updating app data. 當應用程式資料剛完成從雲端同步時,會發生此事件。This event occurs when app data has just finished syncing from the cloud.
  • 漫遊內容的參照而不是原始資料。Roam references to content rather than raw data. 例如,漫遊 URL 而不是線上文章的內容。For example, roam a URL rather than the content of an online article.
  • 對於重要且具時效性的設定,可使用與 RoamingSettings 關聯的 HighPriority 設定。For important, time critical settings, use the HighPriority setting associated with RoamingSettings.
  • 不要漫遊裝置專屬的 app 資料。Don't roam app data that is specific to a device. 有些資訊只與本機相關,如本機檔案資源的路徑名稱。Some info is only pertinent locally, such as a path name to a local file resource. 如果您決定漫遊本機資訊,請確認如果資訊在第二個裝置上無效時,應用程式可以復原它。If you do decide to roam local information, make sure that the app can recover if the info isn't valid on the secondary device.
  • 不要漫遊大量應用程式資料。Don't roam large sets of app data. 應用程式可以漫遊的應用程式資料數量有限;請使用 RoamingStorageQuota 屬性取得此最大值。There's a limit to the amount of app data an app may roam; use RoamingStorageQuota property to get this maximum. 如果應用程式達到這個限制,必須等到應用程式資料存放區的大小不再超過此限制時才能漫遊資料。If an app hits this limit, no data can roam until the size of the app data store no longer exceeds the limit. 設計應用程式時,請考量如何在較大型資料中放置界限,以免超過該限制。When you design your app, consider how to put a bound on larger data so as to not exceed the limit. 例如,如果個別儲存遊戲狀態需要 10KB,則應用程式只能允許使用者儲存最多 10 個遊戲。For example, if saving a game state requires 10KB each, the app might only allow the user store up to 10 games.
  • 不要在依賴立即同步化的資料使用漫遊。Don't use roaming for data that relies on instant syncing. Windows 不保證立即同步化;如果使用者處於離線狀態或使用高延遲網路,可能會嚴重延遲漫遊。Windows doesn't guarantee an instant sync; roaming could be significantly delayed if a user is offline or on a high latency network. 請確定您的 UI 不需要立即同步化。Ensure that your UI doesn't depend on instant syncing.
  • 不要漫遊經常變更的資料。Don't use roaming for frequently changing data. 例如,如果您的應用程式追蹤經常變更的資訊,例如追蹤歌曲每秒的位置,請勿將它儲存為漫遊的應用程式資料。For example, if your app tracks frequently changing info, such as the position in a song by second, don't store this as roaming app data. 請改為挑選較不頻繁但仍提供良好使用者體驗的表示法,像是目前正在播放的歌曲。Instead, pick a less frequent representation that still provides a good user experience, like the currently playing song.

漫遊的先決條件Roaming pre-requisites

如果使用者使用 Microsoft 帳戶登入裝置,便能享有漫遊應用程式資料的好處。Any user can benefit from roaming app data if they use a Microsoft account to log on to their device. 不過,使用者和群組原則系統管理員可以隨時關閉裝置上的漫遊應用程式資料。However, users and group policy administrators can switch off roaming app data on a device at any time. 如果使用者選擇不使用 Microsoft 帳戶或停用漫遊資料功能,還是可以使用您的應用程式,但是應用程式資料將是每個裝置的本機資料。If a user chooses not to use a Microsoft account or disables roaming data capabilities, she will still be able to use your app, but app data will be local to each device.

只有在使用者將裝置設成「受信任」時,才會轉換儲存在 PasswordVault 中的資料。Data stored in the PasswordVault will only transition if a user has made a device “trusted”. 如果裝置不受信任,保存在此保存庫中的資料將不會漫遊。If a device isn't trusted, data secured in this vault will not roam.

衝突的解決方式Conflict resolution

漫遊應用程式資料並不是為了要一次在多個裝置上同時使用。Roaming app data is not intended for simultaneous use on more than one device at a time. 如果同步化時因為兩個裝置上的特定資料單位變更而引發衝突,系統一律保留最後寫入的值。If a conflict arises during synchronization because a particular data unit was changed on two devices, the system will always favor the value that was written last. 這樣可確保應用程式使用的是最新資訊。This ensures that the app utilizes the most up-to-date information. 如果資料單位是一個設定複合項目,則在設定單位的層級仍然會發生衝突解決,這表示將會同步具有最新變更的複合項目。If the data unit is a setting composite, conflict resolution will still occur on the level of the setting unit, which means that the composite with the latest change will be synchronized.

寫入資料的時機When to write data

視設定的預期存留期而定,資料應該在不同時間寫入。Depending on the expected lifetime of the setting, data should be written at different times. 非經常變更或變更緩慢的應用程式資料應該立即寫入。Infrequently or slowly changing app data should be written immediately. 不過,經常變更的應用程式資料應該只在固定的時間間隔 (例如每 5 分鐘一次) 以及應用程式暫停時才定期寫入。However, app data that changes frequently should only be written periodically at regular intervals (such as once every 5 minutes), as well as when the app is suspended. 例如,音樂應用程式可以在開始播放新歌曲時寫入「目前的歌曲」設定,不過,會在暫停時才寫入歌曲的實際位置。For example, a music app might write the “current song” settings whenever a new song starts to play, however, the actual position in the song should only be written on suspend.

過度使用保護Excessive usage protection

系統備有各種適當的保護機制以避免不當使用資源。The system has various protection mechanisms in place to avoid inappropriate use of resources. 如果應用程式資料未依預期方式轉換,有可能是因為裝置暫時受到限制。If app data does not transition as expected, it is likely that the device has been temporarily restricted. 等待一些時間通常能夠自動解決這種情況,不需要採取任何動作。Waiting for some time will usually resolve this situation automatically and no action is required.

版本設定Versioning

應用程式資料可以使用版本設定,將某個資料結構升級為另一個資料結構。App data can utilize versioning to upgrade from one data structure to another. 這種版本號碼不同於應用程式版本,而且能隨意設定。The version number is different from the app version and can be set at will. 雖然不強制,但強烈建議使用遞增的版本號碼,因為在嘗試轉換至代表較新資料的較低資料版本號碼時,可能發生不必要的麻煩 (包括資料遺失)。Although not enforced, it is highly recommended that you use increasing version numbers, since undesirable complications (including data loss)could occur if you try to transition to a lower data version number that represents newer data.

應用程式資料只能在具有相同版本號碼的已安裝應用程式之間漫遊。App data only roams between installed apps with the same version number. 例如,版本 2 的裝置可以彼此互相轉換資料,而版本 3 的裝置也可以同樣彼此轉換資料,但執行版本 2 與執行版本 3 的裝置之間則不會發生漫遊。For example, devices on version 2 will transition data between each other and devices on version 3 will do the same, but no roaming will occur between a device running version 2 and a device running version 3. 如果您安裝使用其他裝置上不同版本號碼的新應用程式,新安裝的應用程式將會同步與最高版本關聯的應用程式資料。If you install a new app that utilized various version numbers on other devices, the newly installed app will sync the app data associated with the highest version number.

測試與工具Testing and tools

開發人員可以鎖定自己的裝置以觸發應用程式資料漫遊同步處理。Developers can lock their device in order to trigger a synchronization of roaming app data. 如果應用程式資料似乎未在某個時間範圍內轉換,請檢查並確定下列項目:If it seems that the app data does not transition within a certain time frame, please check the following items and make sure that:

  • 您的漫遊資料未超過大小上限 (如需詳細資訊,請參閱 RoamingStorageQuota)。Your roaming data does not exceed the maximum size (see RoamingStorageQuota for details).
  • 您的檔案已正確關閉並釋放。Your files are closed and released properly.
  • 至少有兩個裝置執行相同的 app 版本。There are at least two devices running the same version of the app.

登錄以在漫遊資料變更時收到通知Register to receive notification when roaming data changes

若要使用應用程式資料漫遊,您必須登錄漫遊資料變更並擷取漫遊資料容器,以便讀取和寫入設定。To use roaming app data, you need to register for roaming data changes and retrieve the roaming data containers so you can read and write settings.

  1. 登錄以在漫遊資料變更時收到通知。Register to receive notification when roaming data changes.

    DataChanged 事件會在漫遊資料變更時通知您。The DataChanged event notifies you when roaming data changes. 這個範例會將 DataChangeHandler 設定成處理漫遊資料變更的處理常式。This example sets DataChangeHandler as the handler for roaming data changes.

void InitHandlers()
    {
       Windows.Storage.ApplicationData.Current.DataChanged += 
          new TypedEventHandler<ApplicationData, object>(DataChangeHandler);
    }

    void DataChangeHandler(Windows.Storage.ApplicationData appData, object o)
    {
       // TODO: Refresh your data
    }
  1. 取得應用程式各項設定和檔案的容器。Get the containers for the app's settings and files.

    使用 ApplicationData.RoamingSettings 屬性來取得設定,而使用 ApplicationData.RoamingFolder 屬性來取得檔案。Use the ApplicationData.RoamingSettings property to get the settings and the ApplicationData.RoamingFolder property to get the files.

Windows.Storage.ApplicationDataContainer roamingSettings = 
        Windows.Storage.ApplicationData.Current.RoamingSettings;
    Windows.Storage.StorageFolder roamingFolder = 
        Windows.Storage.ApplicationData.Current.RoamingFolder;

建立及擷取漫遊設定Create and retrieve roaming settings

使用 ApplicationDataContainer.Values 屬性存取上一節中取得之 roamingSettings 容器的設定。Use the ApplicationDataContainer.Values property to access the settings in the roamingSettings container we got in the previous section. 此範例會建立名為 exampleSetting 的簡單設定和名為 composite 的複合值。This example creates a simple setting named exampleSetting and a composite value named composite.

// Simple setting

roamingSettings.Values["exampleSetting"] = "Hello World";
// High Priority setting, for example, last page position in book reader app
roamingSettings.values["HighPriority"] = "65";

// Composite setting

Windows.Storage.ApplicationDataCompositeValue composite = 
    new Windows.Storage.ApplicationDataCompositeValue();
composite["intVal"] = 1;
composite["strVal"] = "string";

roamingSettings.Values["exampleCompositeSetting"] = composite;

此範例會擷取我們剛建立的設定。This example retrieves the settings we just created.

// Simple setting

Object value = roamingSettings.Values["exampleSetting"];

// Composite setting

Windows.Storage.ApplicationDataCompositeValue composite = 
   (Windows.Storage.ApplicationDataCompositeValue)roamingSettings.Values["exampleCompositeSetting"];

if (composite == null)
{
   // No data
}
else
{
   // Access data in composite["intVal"] and composite["strVal"]
}

建立及擷取漫遊檔案Create and retrieve roaming files

若要在漫遊 app 資料存放區中建立和更新檔案,請使用檔案 API,例如 Windows.Storage.StorageFolder.CreateFileAsyncWindows.Storage.FileIO.WriteTextAsyncTo create and update a file in the roaming app data store, use the file APIs, such as Windows.Storage.StorageFolder.CreateFileAsync and Windows.Storage.FileIO.WriteTextAsync. 這個範例會在 roamingFolder 容器中建立名為 dataFile.txt 的檔案,然後在這個檔案中寫入目前的日期與時間。This example creates a file named dataFile.txt in the roamingFolder container and writes the current date and time to the file. 來自 CreationCollisionOption 列舉的 ReplaceExisting 值,指出檔案如果已經存在,就會取代它。The ReplaceExisting value from the CreationCollisionOption enumeration indicates to replace the file if it already exists.

async void WriteTimestamp()
{
   Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = 
       new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");

   StorageFile sampleFile = await roamingFolder.CreateFileAsync("dataFile.txt", 
       CreationCollisionOption.ReplaceExisting);
   await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTimeOffset.Now));
}

若要在漫遊 app 資料存放區中開啟和讀取檔案,請使用檔案 API,例如 Windows.Storage.StorageFolder.GetFileAsyncWindows.Storage.StorageFile.GetFileFromApplicationUriAsyncWindows.Storage.FileIO.ReadTextAsyncTo open and read a file in the roaming app data store, use the file APIs, such as Windows.Storage.StorageFolder.GetFileAsync, Windows.Storage.StorageFile.GetFileFromApplicationUriAsync, and Windows.Storage.FileIO.ReadTextAsync. 這個範例會開啟上一節中建立的 dataFile.txt 檔案,然後讀取該檔案的日期。This example opens the dataFile.txt file created in the previous section and reads the date from the file. 如需從各種位置載入檔案資源的詳細資料,請參閱如何載入檔案資源For details on loading file resources from various locations, see How to load file resources.

async void ReadTimestamp()
{
   try
   {
      StorageFile sampleFile = await roamingFolder.GetFileAsync("dataFile.txt");
      String timestamp = await FileIO.ReadTextAsync(sampleFile);
      // Data is contained in timestamp
   }
   catch (Exception)
   {
      // Timestamp not found
   }
}

暫時的 app 資料Temporary app data

暫時的應用程式資料存放區的作用如同快取。The temporary app data store works like a cache. 這個存放區的檔案不會漫遊,並且隨時可以移除。Its files do not roam and could be removed at any time. 系統維護工作可以隨時自動刪除儲存在這個位置的資料。The System Maintenance task can automatically delete data stored at this location at any time. 使用者也可以使用磁碟清理功能來清除暫時的資料存放區檔案。The user can also clear files from the temporary data store using Disk Cleanup. 暫時應用程式資料可以用來儲存應用程式工作階段期間的暫時資訊。Temporary app data can be used for storing temporary information during an app session. 應用程式工作階段結束之後,這些資料不一定會繼續存留,因為系統可能會在需要時回收使用的空間。There is no guarantee that this data will persist beyond the end of the app session as the system might reclaim the used space if needed. 透過 temporaryFolder 屬性可取得此位置。The location is available via the temporaryFolder property.

擷取暫存資料容器Retrieve the temporary data container

使用 ApplicationData.TemporaryFolder 屬性來取得檔案。Use the ApplicationData.TemporaryFolder property to get the files. 下一個步驟會使用這個步驟的 temporaryFolder 變數。The next steps use the temporaryFolder variable from this step.

Windows.Storage.StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder;

建立和讀取暫存檔案Create and read temporary files

若要在暫時的 app 資料存放區中建立和更新檔案,請使用檔案 API,例如 Windows.Storage.StorageFolder.CreateFileAsyncWindows.Storage.FileIO.WriteTextAsyncTo create and update a file in the temporary app data store, use the file APIs, such as Windows.Storage.StorageFolder.CreateFileAsync and Windows.Storage.FileIO.WriteTextAsync. 這個範例會在 temporaryFolder 容器中建立名為 dataFile.txt 的檔案,然後在這個檔案中寫入目前的日期與時間。This example creates a file named dataFile.txt in the temporaryFolder container and writes the current date and time to the file. 來自 CreationCollisionOption 列舉的 ReplaceExisting 值,指出檔案如果已經存在,就會取代它。The ReplaceExisting value from the CreationCollisionOption enumeration indicates to replace the file if it already exists.

async void WriteTimestamp()
{
   Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = 
       new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");

   StorageFile sampleFile = await temporaryFolder.CreateFileAsync("dataFile.txt", 
       CreateCollisionOption.ReplaceExisting);
   await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTimeOffset.Now));
}

若要在暫時的 app 資料存放區中開啟和讀取檔案,請使用檔案 API,例如 Windows.Storage.StorageFolder.GetFileAsyncWindows.Storage.StorageFile.GetFileFromApplicationUriAsyncWindows.Storage.FileIO.ReadTextAsyncTo open and read a file in the temporary app data store, use the file APIs, such as Windows.Storage.StorageFolder.GetFileAsync, Windows.Storage.StorageFile.GetFileFromApplicationUriAsync, and Windows.Storage.FileIO.ReadTextAsync. 這個範例會開啟上一個步驟中建立的 dataFile.txt 檔案,然後讀取該檔案的日期。This example opens the dataFile.txt file created in the previous step and reads the date from the file. 如需從各種位置載入檔案資源的詳細資料,請參閱如何載入檔案資源For details on loading file resources from various locations, see How to load file resources.

async void ReadTimestamp()
{
   try
   {
      StorageFile sampleFile = await temporaryFolder.GetFileAsync("dataFile.txt");
      String timestamp = await FileIO.ReadTextAsync(sampleFile);
      // Data is contained in timestamp
   }
   catch (Exception)
   {
      // Timestamp not found
   }
}

使用容器組織應用程式資料Organize app data with containers

若要適當整理您的應用程式資料設定和檔案,您可以建立容器 (以 ApplicationDataContainer 物件表示),而無須直接使用目錄。To help you organize your app data settings and files, you create containers (represented by ApplicationDataContainer objects) instead of working directly with directories. 您可以將容器新增到本機、漫遊和暫存的應用程式資料存放區。You can add containers to the local, roaming, and temporary app data stores. 容器的巢狀深度最多可達 32 層。Containers can be nested up to 32 levels deep.

若要建立設定容器,請呼叫 ApplicationDataContainer.CreateContainer 方法。To create a settings container, call the ApplicationDataContainer.CreateContainer method. 此範例會建立名為 exampleContainer 的本機設定容器,然後新增名為 exampleSetting 的設定。This example creates a local settings container named exampleContainer and adds a setting named exampleSetting. 來自 ApplicationDataCreateDisposition 列舉的 Always 值,指出如果還沒有容器,就會建立一個容器。The Always value from the ApplicationDataCreateDisposition enumeration indicates that the container is created if it doesn't already exist.

Windows.Storage.ApplicationDataContainer localSettings = 
    Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = 
    Windows.Storage.ApplicationData.Current.LocalFolder;

// Setting in a container
Windows.Storage.ApplicationDataContainer container = 
   localSettings.CreateContainer("exampleContainer", Windows.Storage.ApplicationDataCreateDisposition.Always);

if (localSettings.Containers.ContainsKey("exampleContainer"))
{
   localSettings.Containers["exampleContainer"].Values["exampleSetting"] = "Hello Windows";
}

刪除應用程式設定和容器Delete app settings and containers

若要刪除您的 app 不再需要的簡單設定,請使用 ApplicationDataContainerSettings.Remove 方法。To delete a simple setting that your app no longer needs, use the ApplicationDataContainerSettings.Remove method. 此範例會刪除我們稍早建立的 exampleSetting 本機設定。This example deletesthe exampleSetting local setting that we created earlier.

Windows.Storage.ApplicationDataContainer localSettings = 
    Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = 
    Windows.Storage.ApplicationData.Current.LocalFolder;

// Delete simple setting

localSettings.Values.Remove("exampleSetting");

若要刪除複合設定,請使用 ApplicationDataCompositeValue.Remove 方法。To delete a composite setting, use the ApplicationDataCompositeValue.Remove method. 此範例會刪除我們在先前的範例中建立的 exampleCompositeSetting 複合設定。This example deletes the local exampleCompositeSetting composite setting we created in an earlier example.

Windows.Storage.ApplicationDataContainer localSettings = 
    Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = 
    Windows.Storage.ApplicationData.Current.LocalFolder;

// Delete composite setting

localSettings.Values.Remove("exampleCompositeSetting");

若要刪除容器,請呼叫 ApplicationDataContainer.DeleteContainer 方法。To delete a container, call the ApplicationDataContainer.DeleteContainer method. 此範例會刪除我們稍早建立的本機 exampleContainer 設定。This example deletes the local exampleContainer settings container we created earlier.

Windows.Storage.ApplicationDataContainer localSettings = 
    Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = 
    Windows.Storage.ApplicationData.Current.LocalFolder;

// Delete container

localSettings.DeleteContainer("exampleContainer");

管理應用程式資料的版本Versioning your app data

您可以根據您的需求,為應用程式建立應用程式資料版本。You can optionally version the app data for your app. 如此一來,您就能建立應用程式資料格式會改變的應用程式後續版本,而不會造成與應用程式舊版本的相容性問題。This would enable you to create a future version of your app that changes the format of its app data without causing compatibility problems with the previous version of your app. 應用程式會檢查資料存放區中的應用程式資料版本,如果版本低於應用程式預期的版本,應用程式會將應用程式資料更新成新格式並更新版本。The app checks the version of the app data in the data store, and if the version is less than the version the app expects, the app should update the app data to the new format and update the version. 如需詳細資訊,請參閱 Application.Version 屬性與 ApplicationData.SetVersionAsync 方法。For more info, see the Application.Version property and the ApplicationData.SetVersionAsync method.