Wednesday, April 3, 2013

File IO in Conjunction with WinJS

A type that you used in a .NET Framework doesn't exist within the .NET APIs for Metro style apps. Instead, you can use a type from the Windows Runtime.

For example: the System.IO. Class isn't included in the .NET APIs for Metro style apps but Windows.Storage.ApplicationDataContainer class provides similar behavior for storing app settings.

Before we begin, here are some basic prerequisites details to share about Metro style apps:

Every Metro application has three folders. A Local folder, a Roaming folder and a Temp folder.
  1. Local is meant to store assets in a local, application-specific folder.
  2. Roaming is meant to store assets that should be synchronized with any other desktop where the current user has the same application installed.
  3. Temp is a throw-away location that will be cleaned, potentially, every time the application is launched.

Creating a File on deployed Metro app location:

From the below code snippet, you can see that before creating a file we have to navigate to the storage folder. In this case its local folder where the app is deployed else we can change this location
to the installed location as well.“CreateFileAsync” is the WinJS API That is used to create a file asynchronously.

 var dataFile = "MyFile.txt";

 var appFolder = Windows.Storage.ApplicationData.current.localFolder;
 var option = Windows.Storage.CreationCollisionOption.openIfExists;

 var _file = appFolder.createFileAsync(dataFile, option);

Note: The "CreateFileAsync" API is taking another optional parameter that is “CreationCollisionOption”. Based on this option only, it will create or open the file accordingly.


Writing/Appending text on the File:

So, after creating a file successfully, writing/appending text on file will be again based on
Promise object, as soon as the file will be created or opened if existing, “AppendTextAsync”
API will be appending the data from the last cursor position.

 appFolder.createFileAsync(dataFile, option).then(function (file) {
            Windows.Storage.FileIO.appendTextAsync(file, “Testdata”).done()
        });


Reading text from the File:

So, for reading data from a file firstly, you need to get that file from the directory where is stored and then read the data using “ReadTextAsync” WinJS API.


appFolder.getFileAsync(dataFile).then(
function complete(file) {                                Windows.Storage.FileIO.readTextAsync(file).done(function (text) {
                    var json = text;
                })
            },

            function error(file) {
                //do something
            },

            function progress(file) {
                WinJS.Promise.timeout(5000);
                Windows.Storage.FileIO.readTextAsync(file).done(function (text) {
                    var json = text;
                })
            });


1 comment: