語言

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 需求

規格需求 Description
裝置系列
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 的細節,請參閱 「儲存與取回設定」及其他應用程式資料。

屬性

名稱 Description
Current

提供存取與應用程式套件相關的應用程式資料儲存庫。

LocalCacheFolder

會取得本地應用程式資料庫中的資料夾,在那裡可以儲存未包含在備份和還原中的檔案。

LocalFolder

會取得本地應用程式資料庫中的根目錄。 這個資料夾是備份到雲端的。

LocalSettings

會取得本地應用程式資料儲存庫中的應用程式設定容器。

RoamingFolder

會取得漫遊應用程式資料庫中的根目錄。

RoamingSettings

會取得漫遊應用程式資料庫中的應用程式設定容器。

RoamingStorageQuota

從漫遊應用程式資料庫取得可同步到雲端的最大資料大小。

SharedLocalFolder

會取得共用應用程式資料儲存庫中的根目錄。

TemporaryFolder

會取得臨時應用程式資料庫中的根目錄。

Version

取得應用程式資料庫中應用程式資料的版本號。

方法

名稱 Description
ClearAsync()

移除所有應用程式資料,來自本地、漫遊及暫存應用程式的資料。

備註

如果有任何開啟的檔案位址,ClearAsync() 方法會發生錯誤。 你應該在打電話給 ClearAsync 前,先關閉所有未開啟的檔案。

ClearAsync(ApplicationDataLocality)

從指定的應用程式資料庫移除所有應用程式資料。

備註

如果有任何未開啟的檔案 handle,ClearAsync(ApplicationDataLocality) 方法會發生錯誤。 你應該在打電話給 ClearAsync 前,先關閉所有未開啟的檔案。

ClearPublisherCacheFolderAsync(String)

清除目前應用程式發佈者共用儲存資料夾指定子資料夾中的檔案和子資料夾。

Close()

備註

此成員未在 C# 中實作。

Dispose()

執行與釋放、釋放或重設非受控資源相關聯的應用程式定義工作。

GetForUserAsync(User)

靜態方法,回傳使用者的 ApplicationData。

GetPublisherCacheFolder(String)

取得目前應用程式發佈者共用儲存資料夾指定的子資料夾。

SetVersionAsync(UInt32, ApplicationDataSetVersionHandler)

設定應用程式資料庫中應用程式資料的版本號。

SignalDataChanged()

向所有註冊的事件處理器發送 DataChanged 事件。

事件

名稱 Description
DataChanged

當漫遊應用程式資料同步時會發生。

適用於

另請參閱