Partager via


Quickstart: Local app data (XAML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

Learn how to store and retrieve settings and files from the local app data store.

Roadmap: How does this topic relate to others? See:

Get the containers for the app's settings and files

Use the ApplicationData.LocalSettings property to get the settings in an ApplicationDataContainer object. Use the ApplicationData.LocalFolder property to get the files in a StorageFolder object.

Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Dim localSettings As Windows.Storage.ApplicationDataContainer = Windows.Storage.ApplicationData.Current.LocalSettings
Dim localFolder As Windows.Storage.StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;
StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;

The next sections use the localSettings and localFolder variables from this section.

Write data to a setting

Use the ApplicationDataContainer.Values property to access the settings in the localSettings container we got in the previous step. This example creates a setting named exampleSetting.

// Simple setting

localSettings.Values["exampleSetting"] = "Hello Windows";
' Simple setting

localSettings.Values("exampleSetting") = "Hello Windows";
// Simple setting

auto values = localSettings->Values;
values->Insert("exampleSetting", dynamic_cast<PropertyValue^>(PropertyValue::CreateString("Hello Windows")));

An ApplicationDataCompositeValue object contains settings that must be accessed atomically. This example creates a composite setting named exampleCompositeSetting and adds it to the localSettings container.

// Composite setting

Windows.Storage.ApplicationDataCompositeValue composite = new Windows.Storage.ApplicationDataCompositeValue();
composite["intVal"] = 1;
composite["strVal"] = "string";

localSettings.Values["exampleCompositeSetting"] = composite;
' Composite setting

Dim composite As New Windows.Storage.ApplicationDataCompositeValue
composite("intVal") = 1
composite("strVal") = "string";

localSettings.Values("exampleCompositeSetting") = composite
// Composite setting

ApplicationDataCompositeValue^ composite = ref new ApplicationDataCompositeValue();
composite->Insert("intVal", dynamic_cast<PropertyValue^>(PropertyValue::CreateInt32(1)));
composite->Insert("strVal", dynamic_cast<PropertyValue^>(PropertyValue::CreateString("string")));

auto values = localSettings->Values;
values->Insert("exampleCompositeSetting", composite);

Call the ApplicationDataContainer.CreateContainer method to create a settings container. This example creates a settings container named exampleContainer and adds a setting named exampleSetting. The Always value from the ApplicationDataCreateDisposition enumeration indicates that the container is created if it doesn't already exist.

// Setting in a container

Windows.Storage.ApplicationDataContainer container = 
   localSettings.CreateContainer("exampleContainer", Windows.Storage.ApplicationDataCreateDisposition.Always);

if (localSettings.Containers.ContainsKey("exampleContainer"))
{
   localSettings.Containers["exampleContainer"].Values["exampleSetting"] = "Hello Windows";
}
' Setting in a container

Dim container As Windows.Storage.ApplicationDataContainer = 
   localSettings.CreateContainer("exampleContainer", Windows.Storage.ApplicationDataCreateDisposition.Always)

If localSettings.Containers.ContainsKey("exampleContainer") Then
    localSettings.Containers("exampleContainer").Values("exampleSetting") = "Hello Windows"
End If
// Setting in a container

ApplicationDataContainer^ container = 
   localSettings->CreateContainer("exampleContainer", ApplicationDataCreateDisposition::Always);

if (localSettings->Containers->HasKey("exampleContainer"))
{
   auto values = localSettings->Containers->Lookup("exampleContainer")->Values;
   values->Insert("exampleSetting", "Hello Windows");
}

Read data from a setting

Use the ApplicationDataContainer.Values property to access the exampleSetting setting in the localSettings container.

// Simple setting

Object value = localSettings.Values["exampleSetting"];
' Simple setting

Dim value As Object = localSettings.Values("exampleSetting")
// Simple setting

auto values = localSettings->Values;
String^ value = safe_cast<String^>(localSettings->Values->Lookup("exampleSetting"));

Use the ApplicationDataContainer.Values property to access the exampleCompositeSetting setting in the localSettings container.

// Composite setting

Windows.Storage.ApplicationDataCompositeValue composite = 
   (Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["exampleCompositeSetting"];

if (composite == null)
{
   // No data
}
else
{
   // Access data in composite["intVal"] and composite["strVal"]
}
' Composite setting

Dim composite As Windows.Storage.ApplicationDataCompositeValue = 
   CType(localSettings.Values("exampleCompositeSetting"), Windows.Storage.ApplicationDataCompositeValue)

If composite Is Nothing Then
   ' No data
Else
   ' Access data in composite("intVal") and composite("strVal")
End If
// Composite setting

ApplicationDataCompositeValue^ composite = 
   safe_cast<ApplicationDataCompositeValue^>(localSettings->Values->Lookup("exampleCompositeSetting"));

if (composite == nullptr)
{
   // No data
}
else
{
   int one = safe_cast<IPropertyValue^>(composite->Lookup("intVal"))->GetInt32();
   String^ hello = safe_cast<String^>(composite->Lookup("strVal"));
}

Use the ApplicationDataContainer.Values property to access the exampleSetting setting in the exampleContainer container.

// Setting in a container

bool hasContainer = localSettings.Containers.ContainsKey("exampleContainer");
bool hasSetting = false;

if (hasContainer)
{
   hasSetting = localSettings.Containers["exampleContainer"].Values.ContainsKey("exampleSetting");
}
' Setting in a container

Dim hasContainer As Boolean = localSettings.Containers.ContainsKey("exampleContainer")
Dim hasSetting As Boolean = False

If hasContainer Then
    hasSetting = localSettings.Containers("exampleContainer").Values.ContainsKey("exampleSetting")
End If
// Setting in a container

bool hasContainer = localSettings->Containers->HasKey("exampleContainer");
bool hasSetting = false;

if (hasContainer)
{
   auto values = localSettings->Containers->Lookup("exampleContainer")->Values;
   hasSetting = values->HasKey("exampleSetting");
}

Write data to a file

Use the file APIs, such as Windows.Storage.StorageFolder.CreateFileAsync and Windows.Storage.FileIO.WriteTextAsync, to create and update a file in the local app data store. This example creates a file named dataFile.txt in the localFolder container and writes the current date and time to the file. The ReplaceExisting value from the CreationCollisionOption enumeration indicates to replace the file if it already exists.

Note  For Windows Phone Store apps, app data is backed up by default. If you don't want a file to be backed up, save it in the LocalCache subfolder of the app's local storage.

async void WriteTimestamp()
{
   Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = 
       new Windows.Globalization.DatetimeFormatting.DateTimeFormatter("longtime");

   StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt", 
       CreateCollisionOption.ReplaceExisting);
   await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
}
Imports Windows.Globalization.DateTimeFormatting

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
void MainPage::WriteTimestamp()
{
   concurrency::task<StorageFile^> fileOperation = 
       localFolder->CreateFileAsync("dataFile.txt", CreateCollisionOption::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

Use the file APIs, such as Windows.Storage.StorageFolder.GetFileAsync, Windows.Storage.StorageFile.GetFileFromApplicationUriAsync, and Windows.Storage.FileIO.ReadTextAsync, to open and read a file in the local app data store. This example opens the dataFile.txt file created in the previous step and reads the date from the file. For details on loading file resources from various locations, see How to load file resources.

async void ReadTimestamp()
{
   try
   {
      StorageFile sampleFile = await localFolder.GetFileAsync("dataFile.txt");
      String timestamp = await FileIO.ReadTextAsync(sampleFile);
      // Data is contained in timestamp
   }
   catch (Exception)
   {
      // Timestamp not found
   }
}
Private Async Function ReadTimestamp() As Task
   Try
      Dim sampleFile As StorageFile = Await localFolder.GetFileAsync("dataFile.txt")
      Dim timestamp As string = Await FileIO.ReadTtextAsync(sampleFile)
      ' Data is contained in timestamp
   Catch e1 As Exception
      ' Timestamp not found
   End Try
End Function
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
      }
   });
}

Delete settings when finished with them

Call the ApplicationDataContainerSettings.Remove method to delete the exampleSetting setting when you have finished with it.

// Delete simple setting

localSettings.Values.Remove("exampleSetting");
localSettings.Values.Remove("exampleSetting")
// Delete simple setting

auto values = localSettings->Values;
values->Remove("exampleSetting");

Call the ApplicationDataCompositeValue.Remove method to delete the exampleCompositeSetting composite setting when you have finished with it.

// Delete composite setting

localSettings.Values.Remove("exampleCompositeSetting");
localSettings.Values.Remove("exampleCompositeSetting")
// Delete composite setting

auto values = localSettings->Values;
values->Remove("exampleCompositeSetting");

Call the ApplicationDataContainer.DeleteContainer method to delete the exampleContainer settings container when you have finished with it.

// Delete container

localSettings.DeleteContainer("exampleContainer");
localSettings.DeleteContainer("exampleContainer")
// Delete container

localSettings->DeleteContainer("exampleContainer");

Tasks

How to load file resources

Quickstart: Roaming app data

Quickstart: Temporary app data

Conceptual

Accessing app data with the Windows Runtime

Reference

Windows.Storage.ApplicationData

Windows.Storage.ApplicationDataCompositeValue

Windows.Storage.ApplicationDataContainer

Windows.Storage.ApplicationDataContainerSettings

Samples

Application data sample