Get Path to Temporary File in Windows 8 Metro – Javascript

Creating a temporary file in a Windows 8 Metro app is easy enough, and so is reading it. Just check out the documentation on temporary app data. You really have to dig through additional documentation to find the path to a temporary file in case you need to reference the file itself rather than read its contents. Temporary files go into some sort of elusive folder, which you can reference using the path ms-appdata:///temp/. If you previously saved a temp file called dataFile.txt, its URI will be ms-appdata:///temp/dataFile.txt.

This can be useful if you’re downloading relatively static data from the web that you need to access repeatedly. You can store the response in a temp file and reference it later using the path to your temp file instead of downloading the data again. Or if you’re using a function that only accepts URLs (not variables) you can keep your data in a temporary file and provide the temp file’s URI to that function. The following is an example of how to do just that.

WinJS.xhr({ url: "http://someURL.com" }).then(
   function (result) {
      globalVariables.downloadedData = result;
      writeDataToTempFile();
});

function writeDataToTempFile() {
   temporaryFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
      .then(function (sampleFile) {
         var toWrite = globalVariables.downloadedData;
         return Windows.Storage.FileIO.writeTextAsync(sampleFile, toWrite);
      }).done(function () {      
      });
}

Then read the file contents as you please. Here’s an example using WinJS.xhr a second time, this time to read the temp file rather than downloading the data from the web.

WinJS.xhr({ url: "ms-appdata:///temp/dataFile.txt" }).then(
   function (result) {
      // Do something with the file contents
});

Using WinJS.xhr a second time means you don’t need to create an entirely new function to read the temp file. You can use the same methods to read the temp file that you used to download the file.

About the author

I like learning, programming, and creating. I'm an incessant problem solver, and have an insatiable desire to absorb information. I'm an information sponge. A critical thinker. My left brain and right brain function as one. Business and technology should be one. I invest based on opportunity or technicals, whichever is right. I never let my schooling interfere with my education. Marketing is not fluff, it is data-driven. I find patterns, and analyze the random. I like to teach and explain.

Leave a Reply