Quickstart: Reading and writing files (HTML)
Read and write a file using a StorageFile object.
Prerequisites
-
Understand async programming for Windows Runtime apps using JavaScript
You can learn how to write asynchronous apps in Quickstart: Using promises in JavaScript.
-
Know how to get the file that you want to read from and/or write to
You can learn how to get a file by calling a file picker in Quickstart: Accessing files with file pickers.
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; });
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
sampleFilelike 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
-
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[''] );
-
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
-
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 thetransaction(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 }
-
Use these steps to add code to your
writeToStreamfunction that will write text to your file after the storageFile.openAsync method completes.-
Use the
transactionto 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");
-
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 (
contentsin 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
bufferand uses a dataReader object to read the length of thebuffer, 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
bufferin this way is not especially useful, but you are free to be more creative in how you process thebuffer. 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
-
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 }
-
Use these steps to add code your
readFromStreamfunction that will read text from your file after the storageFile.openAsync method completes.-
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);
-
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.
Related topics
- 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