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,但程式碼可以稍微修改,根據您的資料儲存方式存取 LocalCacheFolderRoamingFolderSharedLocalFolderTemporaryFolderSharedLocalFolder 有一些限制,而且需要特殊許可權才能存取,如需詳細資訊,請參閱 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中,使用者不會在重設裝置或切換至新裝置之後遺失資料。 對於容易重新建立且不需要進行備份和還原的其他類型的本機資料,請使用 LocalCacheFolderTemporaryFolder

LocalCacheFolderTemporaryFolder 都儲存在本機,而且不會備份至雲端。 LocalCacheFolder 控制該應用程式,且在應用程式會話之間持續存在。 LocalCacheFolder 應該用於跨應用程式會話所需的產生內容,例如快取的檔案、記錄或驗證權杖。 TemporaryFolder 不保證在會話之間持續存在,而且可以隨時由系統刪除。

RoamingFolder 通常用於使用者喜好設定和自訂、連結和小型資料檔案。 RoamingFolder的內容會跨使用者的裝置和應用程式實例漫遊。 RoamingFolder 不應該用於大量資料、裝置特定的資料,或依賴立即同步處理的資料。

SharedLocalFolder的另一個資料夾在應用程式使用者帳戶之間是持續性的,而且應該用於多個使用者存取的大型檔案。 需要一些額外的設定,才能存取 SharedLocalFolder。 如需存取和使用這個資料夾的詳細資訊,請參閱 SharedLocalFolder

您可以將應用程式資料儲存在應用程式特定的版本化格式中。 如需詳細資訊,請參閱 VersionSetVersionAsync

如需使用這些 API 的詳細資訊,請參閱 儲存和擷取設定和其他應用程式資料

屬性

Current

提供與應用程式應用程式套件相關聯之應用程式資料存放區的存取權。

LocalCacheFolder

取得本機應用程式資料存放區中的資料夾,您可以在其中儲存備份和還原中未包含的檔案。

LocalFolder

取得本機應用程式資料存放區中的根資料夾。 此資料夾會備份至雲端。

LocalSettings

取得本機應用程式資料存放區中的應用程式設定容器。

RoamingFolder

取得漫遊應用程式資料存放區中的根資料夾。

RoamingSettings

取得漫遊應用程式資料存放區中的應用程式設定容器。

RoamingStorageQuota

取得可從漫遊應用程式資料存放區同步處理至雲端的資料大小上限。

SharedLocalFolder

取得共用應用程式資料存放區中的根資料夾。

TemporaryFolder

取得暫存應用程式資料存放區中的根資料夾。

Version

取得應用程式資料存放區中應用程式資料的版本號碼。

方法

ClearAsync()

從本機、漫遊和暫存應用程式資料存放區中移除所有應用程式資料。

注意

如果有任何開啟的檔案控制碼,ClearAsync () 方法就會發生錯誤。 您應該先小心關閉所有開啟的檔案,再呼叫 ClearAsync。

ClearAsync(ApplicationDataLocality)

從指定的應用程式資料存放區中移除所有應用程式資料。

注意

如果有任何開啟的檔案控制碼,ClearAsync (ApplicationDataLocality) 方法就會發生錯誤。 您應該先小心關閉所有開啟的檔案,再呼叫 ClearAsync。

ClearPublisherCacheFolderAsync(String)

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

Close()

注意

此成員未在 C# 中實作。

Dispose()

執行與釋放 (Free)、釋放 (Release) 或重設 Unmanaged 資源相關聯之應用程式定義的工作。

GetForUserAsync(User)

會傳回User 之 ApplicationData的靜態方法

GetPublisherCacheFolder(String)

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

SetVersionAsync(UInt32, ApplicationDataSetVersionHandler)

設定應用程式資料存放區中應用程式資料的版本號碼。

SignalDataChanged()

DataChanged 事件傳送至所有已註冊的事件處理常式。

事件

DataChanged

在同步處理漫遊應用程式資料時發生。

適用於

另請參閱