Windows 8 How to Write to a File

by sunil ravulapalli /13. January 2012 20:17 /windows8 /Comments (0)

This code was tested on Windows 8 developer preview and may be outdated by the time future versions are released.

Following is the function which takes filename and content and writes content into the file.

 function saveStuff(fileName, contentText) {

        var sampleFile;

        // Create file in user's Document library, overwriting the existing file if there is one
         Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
            sampleFile = file;

            // Have file and text to write
            if (sampleFile != null && geoCode != null) {
                // Open file as stream with read/write access
                sampleFile.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (stream) {
                    // File opened

                    // Prepare and write to the file stream
                    var outputStream = stream.getOutputStreamAt(stream.size);
                    var writer = new Windows.Storage.Streams.DataWriter(outputStream);

                    // Save stream to file
                    writer.storeAsync().then(function () {
                        outputStream.flushAsync().then(function () {
                            writeContent('Geocode saved.');

You can call it as following:

saveStuff('settings.txt', 'blue');
blog comments powered by Disqus