Language

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 に格納されるデータの例を次に示します。

  • アート アプリのユーザー描画
  • フィットネス アプリの毎日の運動履歴
  • todo アプリのショッピング リスト

LocalFolder に情報を格納することで、ユーザーはデバイスをリセットしたり、新しいデバイスに切り替えたりした後にデータを失うわけではありません。 再作成が容易で、バックアップと復元に必要ないその他の種類のローカル データについては、 LocalCacheFolder または TemporaryFolder を使用します。

LocalCacheFolder と TemporaryFolder はどちらもローカルに格納され、クラウドにバックアップされません。 LocalCacheFolder は、そのアプリの制御下にあり、アプリ セッション間で永続的です。 LocalCacheFolder は、キャッシュされたファイル、ログ、認証トークンなど、アプリ セッション間で必要な生成されたコンテンツに使用する必要があります。 TemporaryFolder はセッション間で永続的であるとは限らず、システムはいつでも削除できます。

RoamingFolder は、通常、ユーザー設定とカスタマイズ、リンク、および小さなデータ ファイルに使用されます。 RoamingFolder の内容は、ユーザーのデバイスとアプリ インスタンス間でローミングされます。 RoamingFolder は、大量のデータ、デバイスに固有のデータ、またはインスタント同期に依存するデータには使用しないでください。

別のフォルダー SharedLocalFolder は、アプリ ユーザー アカウント間で永続的であり、複数のユーザーがアクセスする大きなファイルに使用する必要があります。 SharedLocalFolder にアクセスするには、いくつかの追加の設定が必要です。 このフォルダーへのアクセスと使用の詳細については、「 SharedLocalFolder」を参照してください。

アプリ データは、アプリ固有のバージョン管理された形式で格納できます。 詳細については、 Version と SetVersionAsync に関するページを参照してください。

これらの API の使用方法の詳細については、 設定やその他のアプリ データの格納と取得に関するページを参照してください。

プロパティ

Name 説明
Current

アプリのアプリ パッケージに関連付けられているアプリ データ ストアへのアクセスを提供します。

LocalCacheFolder

バックアップと復元に含まれていないファイルを保存できるローカル アプリ データ ストア内のフォルダーを取得します。

LocalFolder

ローカル アプリ データ ストア内のルート フォルダーを取得します。 このフォルダーはクラウドにバックアップされます。

LocalSettings

ローカル アプリ データ ストア内のアプリケーション設定コンテナーを取得します。

RoamingFolder

ローミング アプリ データ ストア内のルート フォルダーを取得します。

RoamingSettings

ローミング アプリ データ ストア内のアプリケーション設定コンテナーを取得します。

RoamingStorageQuota

ローミング アプリ データ ストアからクラウドに同期できるデータの最大サイズを取得します。

SharedLocalFolder

共有アプリ データ ストア内のルート フォルダーを取得します。

TemporaryFolder

一時アプリ データ ストア内のルート フォルダーを取得します。

Version

アプリ データ ストア内のアプリケーション データのバージョン番号を取得します。

メソッド

Name 説明
ClearAsync()

ローカル、ローミング、および一時的なアプリ データ ストアからすべてのアプリケーション データを削除します。

Note

開いているファイル ハンドルがある場合、ClearAsync() メソッドでエラーが発生します。 ClearAsync を呼び出す前に、開いているすべてのファイルを閉じるよう注意する必要があります。

ClearAsync(ApplicationDataLocality)

指定したアプリ データ ストアからすべてのアプリケーション データを削除します。

Note

ClearAsync(ApplicationDataLocality) メソッドは、開いているファイル ハンドルがある場合にエラーを検出します。 ClearAsync を呼び出す前に、開いているすべてのファイルを閉じるよう注意する必要があります。

ClearPublisherCacheFolderAsync(String)

現在のアプリの発行元の共有ストレージ フォルダーの指定したサブフォルダーからファイルとサブフォルダーをクリアします。

Close()

Note

このメンバーは C# では実装されていません。

Dispose()

アンマネージド リソースの解放、解放、またはリセットに関連付けられているアプリケーション定義のタスクを実行します。

GetForUserAsync(User)

ユーザーの ApplicationData を返す静的メソッド。

GetPublisherCacheFolder(String)

現在のアプリの発行元の共有ストレージ フォルダーの指定されたサブフォルダーを取得します。

SetVersionAsync(UInt32, ApplicationDataSetVersionHandler)

アプリ データ ストア内のアプリケーション データのバージョン番号を設定します。

SignalDataChanged()

登録されているすべてのイベント ハンドラーに DataChanged イベントを送信します。

イベント

Name 説明
DataChanged

ローミング アプリケーション データが同期されるときに発生します。

適用対象

関連項目