共用方式為


快速入門:暫時的應用程式資料 (HTML)

[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]

了解如何從暫時的應用程式資料存放區儲存與抓取檔案。

取得應用程式檔案的容器

使用 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

範例

應用程式資料範例