Share via


Quickstart: Reading and writing files (HTML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Read and write a file using a StorageFile object.

Prerequisites

The file used in the examples

All the code in these examples is taken from the File access sample and depends on the sample's global sampleFile variable. This variable represents the file (sample.dat) that the sample writes to and reads from in the examples.

The File access sample creates the sample.dat file and stores the storageFile object that is returned, like this:

Windows.Storage.ApplicationData.current.localFolder.createFileAsync("sample.dat",
    Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
        sampleFile = file;
    });

Note  Before you can create files in libraries, you must declare the necessary capabilities in your app manifest. To learn more about file access and capabilities, see File access and permissions and Access to user resources using the Windows Runtime.

 

Writing to a file

These steps show you how to write to a file if you have a writable file and a storageFile that represents it.

Writing text to a file

Write text to your file by calling the writeTextAsync methods of the fileIO class.

The File access sample shows you how to call writeTextAsync(file, contents) to write some arbitrary text to its sampleFile like this:

Windows.Storage.FileIO.writeTextAsync(sampleFile, "Swift as a shadow").then(function () {
    // Add code to do something after the text is written to the file
});

Although the writeTextAsync methods do not have a return value, you can still use then or done to declare a function and perform additional tasks after the text is written to the file, as the sample shows.

Writing bytes to a file by using a buffer

  1. Get a buffer of the bytes that you want to write to your file.

    For example, the File access sample calls convertStringToBinary to get a buffer of bytes based on an arbitrary string, like this:

    var buffer = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(
        'What fools these mortals be', Windows.Security.Cryptography.BinaryStringEncoding['']
    );
    
  2. Write the bytes from your buffer to your file by calling the writeBufferAsync method of the fileIO class.

    The File access sample shows you how to use writeBufferAsync to write bytes from a buffer to its sampleFile, like this:

    Windows.Storage.FileIO.writeBufferAsync(sampleFile, buffer).then(function () {
        // Add code to do something after the text is written to the file
    });
    

    Although writeBufferAsync does not have a return value, you can still use then or done to declare a function and perform additional tasks after the text is written to the file, as the sample shows.

Writing text to a file by using a transacted stream

  1. Open a stream to your file by calling the storageFile.openTransactedWriteAsync method. It returns a stream of the file's content when the open operation completes.

    The File access sample shows you how to open a stream over a file (sampleFile) by calling the storageFile.openTransactedWriteAsync method, like this:

    sampleFile.openTransactedWriteAsync().then(writeToStream);
    

    Make sure you declare a function (like writeToStream) to capture the transaction (type StorageStreamTransaction) so that you can write to your file after the method completes, like this:

    function writeToStream(transaction) {
        // Add code to use the stream to write to your file
    }
    
  2. Use these steps to add code to your writeToStream function that will write text to your file after the storageFile.openAsync method completes.

    1. Use the transaction to write text to stream by creating a new dataWriter object and calling the dataWriter.writeString method.

      The File access sample shows you how to write text to the stream like this:

      var dataWriter = new Windows.Storage.Streams.DataWriter(transaction.stream);
      dataWriter.writeString("Swift as a shadow");
      
    2. Save the text to your file and close the stream by calling the dataWriter.storeAsync and transaction.commitAsync methods.

      The File access sample shows you how to save the text to your file and close the stream, like this:

      dataWriter.storeAsync().then(function () {
          transaction.commitAsync().done(function () {
              // Text in stream has been saved to the file
              transaction.close();
          });
      });
      

You can download the File access sample to see these code examples in context inside functions.

Reading from a file

These steps show you how to read from a file if you have a readable file and a storageFile that represents it.

Reading text from a file

Read text from your file by calling the readTextAsync methods of the fileIO class.

The File access sample shows you how to read text from a file by calling readTextAsync(file) to read from its sampleFile, like this:

Windows.Storage.FileIO.readTextAsync(sampleFile).then(function (contents) {
    // Add code to process the text read from the file
});

You can use then or done to declare a function to capture and process the text that was read from the file. After the readTextAsync method completes, the text is passed to this function as a String object (contents in the sample).

Reading bytes from a file by using a buffer

Read bytes from your file into your buffer by calling the readBufferAsync method of the fileIO class.

The File access sample shows you how to read bytes to a buffer from a file by calling readBufferAsync, like this:

Windows.Storage.FileIO.readBufferAsync(sampleFile).then(function (buffer) {
    // Add code to process the text read from the file
});

You can use then or done to declare a function to capture and process the buffer (type IBuffer) data after the readBufferAsync method completes.

For example, the File access sample captures the buffer and uses a dataReader object to read the length of the buffer, like this:

Windows.Storage.FileIO.readBufferAsync(sampleFile).then(function (buffer) {
    var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
    var output = dataReader.readString(buffer.length);
});

Of course, reading the length of the buffer in this way is not especially useful, but you are free to be more creative in how you process the buffer. You might take a look at the methods available from the dataReader class to get some idea of what you could do.

Reading text from a file by using a stream

  1. Open a stream from your file by calling the storageFile.openAsync method. It returns a stream of the file's content when the open operation completes.

    The File access sample shows you how to open a stream over a file (sampleFile) by calling the storageFile.openAsync method like this:

    sampleFile.openAsync(Windows.Storage.FileAccessMode.readWrite).then(readFromStream);
    

    Make sure you declare a function (like readFromStream) to capture the stream (type IRandomAccessStream) so that you can read from it after the method completes, like this:

    function readFromStream(readStream) {
        // Add code to use the stream to read text from your file
    }
    
  2. Use these steps to add code your readFromStream function that will read text from your file after the storageFile.openAsync method completes.

    1. Get a dataReader object to read from the readStream.

      The File access sample shows how to get a dataReader like this:

      var dataReader = new Windows.Storage.Streams.DataReader(readStream);
      
    2. Read the text by calling the dataReader.loadAsync and dataReader.readString methods.

      The File access sample shows you how to read text like this:

      
      dataReader.loadAsync(readStream.size).done(function (numBytesLoaded) {
          var fileContent = dataReader.readString(numBytesLoaded);
          // Process text read from the file
          dataReader.close();
      });
      

You can download the File access sample to see these code examples in context inside functions.

Summary and next steps

You should now understand how to read and write from a file if you have a storageFile that represents the file.

To learn about working with image files, see How to select and display an image or How to decode an image and the Using a Blob to save and load content sample.

Accessing data from files

Quickstart: Accessing files with file pickers

How to select and display an image

How to decode an image

File access and permissions

File access sample

Using a Blob to save and load content sample

Reference

Windows.Storage.StorageFile class

Windows.Storage.Streams.DataReader class

Windows.Storage.Streams.DataWriter class