存储和检索设置以及其他应用数据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 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. 用户数据可能对于多个应用都非常有用或有意义。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.

关于应用数据的重要说明: 应用数据的生命周期与应用的生命周期相关联。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. 不要使用应用数据存储用户数据或用户可能视作有价值和不可替代内容的任何数据。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 data is ideal for storing app-specific user preferences, settings, and favorites.

应用数据类型Types of app data

应用数据有两类:设置和文件。There are two types of app data: settings and files.

SettingsSettings

使用设置存储用户首选项和应用程序状态信息。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
  • DateTimeTimeSpan DateTime, 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.

在应用数据存储中存储应用数据Storing app data in the app data stores

安装应用时,系统会为设置和文件提供它自己的每用户数据存储。When an app is installed, the system gives it its own per-user data stores for settings and files. 你不需要知道这些数据位于何处或如何存储,因为系统会负责管理物理存储工作,这样可确保数据与其他应用和用户保持隔离状态。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. 系统还在用户向应用安装更新时保留这些数据存储的内容,并在卸载应用时完全且干净地删除这些数据存储的内容。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. 若要检索本地应用数据存储,请使用 ApplicationData.LocalSettings 属性获取应用作为 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 属性来获取保存不包括在备份和还原中的文件的本地应用数据存储中的文件夹。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

若要创建和更新本地应用数据存储中的文件,请使用文件 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));
}

若要打开本地应用数据存储中的文件,请使用文件 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. OS 在漫游数据更新时将它复制到云,并将该数据同步到已安装应用的其他设备。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. 如果用户在该时间间隔内重新安装该应用,则会从云中同步漫游数据。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.
  • 不要漫游特定于设备的应用数据。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.
  • 至少存在两台运行相同应用版本的设备。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

若要在漫游应用数据存储中创建和更新文件,请使用文件 API(如 Windows.Storage.StorageFolder.CreateFileAsyncWindows.Storage.FileIO.WriteTextAsync)。To 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));
}

若要在漫游应用数据存储中打开和读取文件,请使用文件 API(如 Windows.Storage.StorageFolder.GetFileAsyncWindows.Storage.StorageFile.GetFileFromApplicationUriAsyncWindows.Storage.FileIO.ReadTextAsync)。To 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
   }
}

临时应用数据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

若要在临时应用数据存储中创建和更新文件,请使用文件 API(如 Windows.Storage.StorageFolder.CreateFileAsyncWindows.Storage.FileIO.WriteTextAsync)。To 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));
}

若要在临时应用数据存储中打开和读取文件,请使用文件 API(如 Windows.Storage.StorageFolder.GetFileAsyncWindows.Storage.StorageFile.GetFileFromApplicationUriAsyncWindows.Storage.FileIO.ReadTextAsync)。To 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

若要删除应用不再需要的简单设置,请使用 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.