ApplicationData 类 
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
提供对应用程序数据存储的访问权限。 应用程序数据由本地、漫游或临时的文件和设置组成。
public ref class ApplicationData sealedpublic ref class ApplicationData sealed : IClosable/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.MTA)]
class ApplicationData final/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.MTA)]
class ApplicationData final : IClosable[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.MTA)]
public sealed class ApplicationData[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.MTA)]
public sealed class ApplicationData : System.IDisposablePublic NotInheritable Class ApplicationDataPublic NotInheritable Class ApplicationData
Implements IDisposable- 继承
- 属性
- 实现
Windows 要求
| 设备系列 | 
							Windows 10 (在 10.0.10240.0 中引入) | 
| API contract | 
							Windows.Foundation.UniversalApiContract (在 v1.0 中引入) | 
示例
下面的代码示例演示如何读取或写入所选的 ApplicationData 文件夹。 此示例使用 LocalFolder,但可以稍微修改代码,以便根据数据的存储方式访问 LocalCacheFolder、 RoamingFolder、 SharedLocalFolder 或 TemporaryFolder 。 SharedLocalFolder 有一些限制,需要特殊权限才能访问,有关详细信息,请参阅 SharedLocalFolder。
// This example code can be used to read or write to an ApplicationData folder of your choice.
// Change this to Windows.Storage.StorageFolder roamingFolder = Windows.Storage.ApplicationData.Current.RoamingFolder;
// to use the RoamingFolder instead, for example.
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
// Write data to a file
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(DateTime.Now));
}
// Read data from a file
async Task ReadTimestamp()
{
    try
    {
        StorageFile sampleFile = await localFolder.GetFileAsync("dataFile.txt");
        String timestamp = await FileIO.ReadTextAsync(sampleFile);
        // Data is contained in timestamp
    }
    catch (FileNotFoundException e)
    {
        // Cannot find file
    }
    catch (IOException e)
    {
        // Get information from the exception, then throw
        // the info to the parent method.
        if(e.Source != null)
        {
            Debug.WriteLine("IOException source: {0}", e.Source);
        }
        throw;
    }
}
#include <winrt/Windows.Globalization.h>
#include <winrt/Windows.Globalization.DateTimeFormatting.h>
#include <winrt/Windows.Storage.h>
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Storage;
using namespace Windows::UI::Xaml;
// This example code can be used to read or write to an ApplicationData folder of your choice.
// Change this to StorageFolder m_localFolder{ Windows::Storage::ApplicationData::Current().RoamingFolder() }; to 
// use the RoamingFolder instead, for example.
StorageFolder m_localFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() };
// Write data to a file.
IAsyncAction MainPage::WriteTimestampAsync()
{
    StorageFile sampleFile{ co_await m_localFolder.CreateFileAsync(L"dataFile.txt", CreationCollisionOption::ReplaceExisting) };
    Windows::Globalization::Calendar calendar;
    auto now = calendar.GetDateTime();
    Windows::Globalization::DateTimeFormatting::DateTimeFormatter formatter{ L"longtime" };
    try
    {
        co_await FileIO::WriteTextAsync(sampleFile, formatter.Format(now));
    }
    catch (winrt::hresult_error const& /* ex */)
    {
        // Timestamp not written.
    }
}
// Read data from a file.
IAsyncAction MainPage::ReadTimestampAsync()
{
    StorageFile file{ co_await m_localFolder.GetFileAsync(L"dataFile.txt") };
    try
    {
        winrt::hstring timestamp{ co_await Windows::Storage::FileIO::ReadTextAsync(file) };
    }
    catch (winrt::hresult_error const& /* ex */)
    {
        // Timestamp not read.
    }
}
IAsyncAction MainPage::ClickHandler(IInspectable const&, RoutedEventArgs const&)
{
    myButton().Content(box_value(L"Clicked"));
    co_await WriteTimestampAsync();
    co_await ReadTimestampAsync();
}
// This example code can be used to read or write to an ApplicationData folder of your choice.
// Change this to StorageFolder^ roamingFolder = ApplicationData::Current->RoamingFolder; to 
// use the RoamingFolder instead, for example.
StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;
// Write data to a file
void MainPage::WriteTimestamp()
{
   concurrency::task<StorageFile^> fileOperation = 
       localFolder->CreateFileAsync("dataFile.txt", CreationCollisionOption::ReplaceExisting);
   fileOperation.then([this](StorageFile^ sampleFile)
   {
      auto calendar = ref new Calendar;
      auto now = calendar->ToDateTime();
      auto formatter = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("longtime");
      return FileIO::WriteTextAsync(sampleFile, formatter->Format(now));
   }).then([this](task<void> previousOperation) {
      try {
         previousOperation.get();
      } catch (Platform::Exception^) {
         // Timestamp not written
      }
   });
}
// Read data from a file
void MainPage::ReadTimestamp()
{
   concurrency::task<StorageFile^> getFileOperation(localFolder->GetFileAsync("dataFile.txt"));
   getFileOperation.then([this](StorageFile^ file)
   {
      return FileIO::ReadTextAsync(file);
   }).then([this](concurrency::task<String^> previousOperation) {
      String^ timestamp;
      try {
         // Data is contained in timestamp
         timestamp = previousOperation.get();
      } catch (...) {
         // Timestamp not found
      }
   });
}
' This example code can be used to read or write to an ApplicationData folder of your choice.
' Change this to Dim roamingFolder As Windows.Storage.StorageFolder = Windows.Storage.ApplicationData.Current.RoamingFolder
' to use the RoamingFolder instead, for example.
Dim localFolder As Windows.Storage.StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
' Write data to a file
Private Async Sub WriteTimestamp()
   Dim formatter As DateTimeFormatter = New DateTimeFormatter("longtime")
   Dim sampleFile As StorageFile = Await localFolder.CreateFileAsync("dataFile.txt", 
       CreationCollisionOption.ReplaceExisting)
   Await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
End Sub
' Read data from a file
Private Async Function ReadTimestamp() As Task
   Try
      Dim sampleFile As StorageFile = Await localFolder.GetFileAsync("dataFile.txt")
      Dim timestamp As string = Await FileIO.ReadTextAsync(sampleFile)
      ' Data is contained in timestamp
   Catch e1 As Exception
      ' Timestamp not found
   End Try
End Function
有关读取和写入文件的详细信息,请参阅 创建、写入和读取文件。
注解
应用程序数据类型
ApplicationData 为每个用户的应用数据提供本地、漫游和临时存储。 使用此类可在会话、用户之间以及跨多个设备保留特定于应用的数据。
ApplicationData 不提供对应用包中的文件的访问权限。 为此,请使用 Windows.ApplicationModel.Package.InstalledLocation。
ApplicationData.Current 提供应用的 ApplicationData 实例。 使用此实例获取应用文件夹或设置。
文件夹用于将应用数据存储为文件系统上的文件。 应用设置存储在键/值对中,这些键/值对可以组织到嵌套集。 设置数据保存在 Windows 注册表中。
以下是main类型的应用数据:
- 本地:存储在设备上,在云中备份,并在更新之间持久保存
- LocalCache:当前设备上存在的、未备份且在更新之间保留的永久性数据
- SharedLocal:在所有应用用户中持久
- 漫游:存在于用户安装了应用的所有设备上
- 临时:系统可以随时删除
使用应用程序文件夹
LocalFolder 在更新中保持不变,并作为设备备份的一部分备份到云中。 通常,此文件夹应用于未备份时丢失的用户数据。 存储在 LocalFolder 中的数据的一些示例如下:
- 艺术应用的用户绘图
- 健身应用的日常运动历史记录
- Todo 应用的购物列表 通过在 LocalFolder 中存储信息,用户在重置设备或切换到新设备后不会丢失数据。 对于易于重新创建且不需要备份和还原的其他类型的本地数据,请使用 LocalCacheFolder 或 TemporaryFolder。
LocalCacheFolder 和 TemporaryFolder 都存储在本地,不会备份到云中。 LocalCacheFolder 受该应用的控制,并且跨应用会话持续存在。 LocalCacheFolder 应用于应用会话之间所需的生成内容,例如缓存的文件、日志或身份验证令牌。 不保证 TemporaryFolder 在会话中永久存在,系统可以随时删除。
RoamingFolder 通常用于用户首选项和自定义、链接和小型数据文件。 RoamingFolder 在用户的设备和应用实例之间漫游的内容。 RoamingFolder 不应用于大量数据、特定于设备的数据或依赖于即时同步的数据。
另一个文件夹 SharedLocalFolder 在应用用户帐户中是永久性的,应该用于多个用户访问的大型文件。 访问 SharedLocalFolder 需要一些额外的设置。 有关访问和使用此文件夹的详细信息,请参阅 SharedLocalFolder。
你可以以特定于应用的版本控制格式存储应用数据。 有关详细信息,请参阅 Version 和 SetVersionAsync。
有关使用这些 API 的更多详细信息,请参阅 存储和检索设置和其他应用数据。
属性
| Current | 提供对与应用的应用包关联的应用数据存储的访问权限。 | 
| LocalCacheFolder | 获取本地应用数据存储中的文件夹,可在其中保存备份和还原中未包含的文件。 | 
| LocalFolder | 获取本地应用数据存储中的根文件夹。 此文件夹将备份到云中。 | 
| LocalSettings | 获取本地应用数据存储中的应用程序设置容器。 | 
| RoamingFolder | 获取漫游应用数据存储中的根文件夹。 | 
| RoamingSettings | 获取漫游应用数据存储中的应用程序设置容器。 | 
| RoamingStorageQuota | 获取可从漫游应用数据存储同步到云的最大数据大小。 | 
| SharedLocalFolder | 获取共享应用数据存储中的根文件夹。 | 
| TemporaryFolder | 获取临时应用数据存储中的根文件夹。 | 
| Version | 获取应用数据存储区中应用程序数据的版本号。 | 
方法
| ClearAsync() | 从本地、漫游和临时应用数据存储中删除所有应用程序数据。 注意 如果有任何打开的文件句柄,ClearAsync () 方法遇到错误。 在调用 ClearAsync 之前,应小心关闭所有打开的文件。 | 
| ClearAsync(ApplicationDataLocality) | 从指定的应用数据存储中删除所有应用程序数据。 注意 如果有任何打开的文件句柄,ClearAsync (ApplicationDataLocality) 方法遇到错误。 在调用 ClearAsync 之前,应小心关闭所有打开的文件。 | 
| ClearPublisherCacheFolderAsync(String) | 清除当前应用的发布者的共享存储文件夹的指定子文件夹中的文件和子文件夹。 | 
| Close() | 注意 此成员未在 C# 中实现。 | 
| Dispose() | 执行与释放或重置非托管资源关联的应用程序定义的任务。 | 
| GetForUserAsync(User) | 返回用户的ApplicationData 的静态方法。 | 
| GetPublisherCacheFolder(String) | 获取当前应用的发布者的共享存储文件夹的指定子文件夹。 | 
| SetVersionAsync(UInt32, ApplicationDataSetVersionHandler) | 设置应用数据存储区中应用程序数据的版本号。 | 
| SignalDataChanged() | 将 DataChanged 事件发送到所有已注册的事件处理程序。 | 
事件
| DataChanged | 同步漫游应用程序数据时发生。 |