快速入门:临时应用数据 (HTML)

[ 本文适用于编写 Windows 运行时应用的 Windows 8.x 和 Windows Phone 8.x 开发人员。如果你要针对 Windows 10 进行开发,请参阅 最新文档 ]

了解存储和检索临时应用数据存储中的文件的相关信息。

为应用的文件获取容器

使用 ApplicationData.temporaryFolder 属性获取文件。后续步骤使用此步骤中的 temporaryFolder 变量。


var applicationData = Windows.Storage.ApplicationData.current;
var temporaryFolder = applicationData.temporaryFolder;

将数据写入文件

使用文件 API(如 Windows.Storage.StorageFolder.createFileAsyncWindows.Storage.FileIO.writeTextAsync)在临时应用数据存储中创建和更新文件。此示例会在 temporaryFolder 容器中创建一个名为 dataFile.txt 的文件并将当前日期和时间写入该文件中。CreationCollisionOption 枚举中的 replaceExisting 值指示替换该文件(如果存在的话)。

function writeTimestamp() {
   temporaryFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
      .then(function (sampleFile) {
         var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
         var timestamp = formatter.format(new Date());

         return Windows.Storage.FileIO.writeTextAsync(sampleFile, timestamp);
      }).done(function () {      
      });
}

从文件中读取数据

使用文件 API(如 Windows.Storage.StorageFolder.getFileAsyncWindows.Storage.StorageFile.GetFileFromApplicationUriAsyncWindows.Storage.FileIO.readTextAsync)在临时应用数据存储中打开和读取文件。此示例打开在上一步中创建的 dataFile.txt 文件并从该文件中读取日期。CreationCollisionOption 枚举中的 openIfExists 值指示该文件必须存在。有关从多个位置加载文件资源的详细信息,请参阅如何加载文件资源

function readTimestamp() {
   temporaryFolder.getFileAsync("dataFile.txt")
      .then(function (sampleFile) {
         return Windows.Storage.FileIO.readTextAsync(sampleFile);
      }).done(function (timestamp) {
         // Data is contained in timestamp
      }, function () {
         // Timestamp not found
      });
}

相关主题

任务

如何加载文件资源

快速入门:本地应用数据

快速入门:漫游应用数据

概念

使用 Windows 运行时访问应用数据

参考

Windows.Storage.ApplicationData

Windows.Storage.ApplicationDataCompositeValue

Windows.Storage.ApplicationDataContainer

Windows.Storage.ApplicationDataContainerSettings

示例

应用数据示例