语言

ApplicationData 类

定义

提供对应用程序数据存储的访问权限。 应用程序数据由本地、漫游或临时的文件和设置组成。

public ref class ApplicationData sealed
public 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.IDisposable
Public NotInheritable Class ApplicationData
Public NotInheritable Class ApplicationData
Implements IDisposable
继承
Object Platform::Object IInspectable ApplicationData
属性
实现

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注册表中。

以下是应用数据的主要类型:

  • 本地:存储在设备上、备份在云中,并在更新之间保留
  • LocalCache:当前设备上存在的持久性数据,未备份,并且跨更新持久保存
  • SharedLocal:跨所有应用用户持久
  • 漫游:存在于用户已安装应用的所有设备上
  • 临时:随时可由系统删除

使用应用程序文件夹

LocalFolder 会持续更新,并在设备备份过程中备份到云。 通常,此文件夹应用于未备份时丢失的用户数据。 LocalFolder 中存储的一些数据示例包括:

  • 艺术应用的用户绘图
  • 健身应用的每日锻炼历史记录
  • 待办事项应用的购物列表

通过将信息存储在 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)

返回 User 的 ApplicationData 的静态方法。

GetPublisherCacheFolder(String)

获取当前应用的发布者的共享存储文件夹的指定子文件夹。

SetVersionAsync(UInt32, ApplicationDataSetVersionHandler)

设置应用数据存储中的应用程序数据的版本号。

SignalDataChanged()

将 DataChanged 事件发送到所有已注册的事件处理程序。

事件

名称 说明
DataChanged

同步漫游应用程序数据时发生。

适用于

另请参阅