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 instance 제공합니다. 이 instance 사용하여 앱 폴더 또는 설정을 가져옵니다.

폴더는 앱 데이터를 파일 시스템에 파일로 저장하는 데 사용됩니다. 앱 설정은 중첩된 집합으로 구성할 수 있는 키/값 쌍에 저장됩니다. 설정 데이터는 Windows 레지스트리에 저장됩니다.

다음은 앱 데이터의 기본 유형입니다.

  • 로컬: 디바이스에 저장되고, 클라우드에 백업되고, 업데이트 간에 유지됩니다.
  • LocalCache: 현재 디바이스에 있고 백업되지 않고 업데이트 간에 유지되는 영구 데이터
  • SharedLocal: 모든 앱 사용자에 대해 영구적
  • 로밍: 사용자가 앱을 설치한 모든 디바이스에 있음
  • 임시: 언제든지 시스템에서 삭제할 수 있습니다.

애플리케이션 폴더 사용

LocalFolder 는 업데이트 간에 유지되며 디바이스 백업의 일부로 클라우드에 백업됩니다. 일반적으로 이 폴더는 백업되지 않은 경우 손실되는 사용자 데이터에 사용해야 합니다. LocalFolder에 저장된 데이터의 몇 가지 예는 다음과 같습니다.

  • 아트 앱에 대한 사용자 드로잉
  • 피트니스 앱의 일일 운동 기록
  • 할 일 앱의 쇼핑 목록 LocalFolder에 정보를 저장하면 디바이스를 다시 설정하거나 새 디바이스로 전환한 후 데이터가 손실되지 않습니다. 다시 만들기 쉽고 백업 및 복원에 필요하지 않은 다른 유형의 로컬 데이터의 경우 LocalCacheFolder 또는 TemporaryFolder를 사용합니다.

LocalCacheFolderTemporaryFolder 는 모두 로컬로 저장되며 클라우드에 백업되지 않습니다. LocalCacheFolder 는 해당 앱을 제어하며 앱 세션 간에 지속됩니다. LocalCacheFolder 는 캐시된 파일, 로그 또는 인증 토큰과 같은 앱 세션에서 필요한 생성된 콘텐츠에 사용해야 합니다. TemporaryFolder 는 세션 간에 지속되도록 보장되지 않으며 언제든지 시스템에서 삭제할 수 있습니다.

RoamingFolder 는 일반적으로 사용자 기본 설정 및 사용자 지정, 링크 및 작은 데이터 파일에 사용됩니다. RoamingFolder의 콘텐츠는 사용자의 디바이스 및 앱 인스턴스에서 로밍됩니다. RoamingFolder는 대량의 데이터, 디바이스와 관련된 데이터 또는 즉각적인 동기화에 의존하는 데이터에 사용하면 안 됩니다.

또 다른 폴더 SharedLocalFolder는 앱 사용자 계정에서 지속되며 여러 사용자가 액세스하는 대용량 파일에 사용해야 합니다. SharedLocalFolder에 액세스하려면 몇 가지 추가 설정이 필요합니다. 이 폴더에 액세스하고 사용하는 방법에 대한 자세한 내용은 SharedLocalFolder를 참조하세요.

앱별 버전이 지정된 형식으로 앱 데이터를 저장할 수 있습니다. 자세한 내용은 버전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

로밍 애플리케이션 데이터가 동기화될 때 발생합니다.

적용 대상

추가 정보