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 を使用しますが、データの格納方法に基づいて LocalCacheFolderRoamingFolderSharedLocalFolder、または 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 を使用します。

LocalCacheFolderTemporaryFolder はどちらもローカルに格納され、クラウドにバックアップされません。 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)

UserApplicationData を返す静的メソッド。

GetPublisherCacheFolder(String)

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

SetVersionAsync(UInt32, ApplicationDataSetVersionHandler)

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

SignalDataChanged()

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

イベント

DataChanged

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

適用対象

こちらもご覧ください