Udostępnij za pośrednictwem


File handling, start to finish

[ 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 ]

Learn how to add file-handling capabilities to your Windows Store app using JavaScript and running on Windows 8.1.

Each section of this topic describes a key file-handling feature, links to a topic that provides more detail on that feature, and offers info about how to quickly find the relevant code in this topic's companion File handling, start to finish companion sample.

Note  Many of the functions used to interact with folders and files are asynchronous. You can learn how to write asynchronous JavaScript apps in Asynchronous programming in JavaScript.

 

File access basics: enumerating, getting properties, and reading and writing data

step icon Quickstart: Accessing files programmatically

You can access files in a location such as a folder, library, device, or network location, with just a single line of code—a call to the StorageFolder.getFilesAsync function. See Accessing files programmatically for step-by-step instructions that show how to perform tasks like enumerating the top-level files and folders of a specified location and querying files in a location.

These steps show you how to enumerate files in a particular location:

  1. Acquire a StorageFolder object for the location you want. For example, you can do this by referencing one of the static KnownFolders properties - such as KnowFolders.picturesLibrary.
  2. Call the returned StorageFolder object's StorageFolder.getFilesAsync function. This topic's companion sample calls this method without any parameters, indicating that all files should be returned. To see examples of calling the StorageFolder.getFilesAsync with a query, refer to Quickstart: Accessing files programmatically.
  3. Once the StorageFolder.getFilesAsync function is complete, you can use a forEach loop to iterate over each returned file.

This code example enumerates all files in Pictures.


// Get a StorageFolder object representing Pictures.
var library = Windows.Storage.KnownFolders.picturesLibrary;

// Get all files from the StorageFolder object.
library.getFilesAsync().then(function (files) {
    // For each file found ...
    files.forEach(function (file) {
        // ... perform your processing.
        });
    });
}

This screen shot from the companion sample shows an example of enumerating the files in Pictures.

File-handling sample screen shot of enumerating files in the Pictures library.

Find it in the sample: The sample includes a page titled FileAccessBasics, which includes the examples presented in this section. The relevant JavaScript and HTML code is centralized to the FileAccessBasicsPage.js (OnEnumPicturesClick function) and FileAccessBasicsPage.html files.

step icon

Quickstart: Getting a file's properties

File properties describe or quantify an attribute of a file or its contents. For example, file properties include data such as file name, path, file size, file attributes, and date last accessed. Quickstart: Getting a file's properties shows how to retrieve and display a file's top-level and basic properties.

These steps show you how to get either top-level or basic file properties:

This code example enumerates all files in Pictures and displays various top-level and basic file properties. Note how JavaScript promises are being used to synchronize the results of two asynchronous operations (StorageFolder.getFilesAsync and StorageFile.getBasicPropertiesAsync). To learn more about asynchronous programming and promises in JavaScript, refer to Asynchronous programming in JavaScript.


// Get a StorageFolder object representing the Pictures Library.
var library = Windows.Storage.KnownFolders.picturesLibrary;

// Initialize string that holds all property information.
var outString = "";

// Get all files from the StorageFolder object.
library.getFilesAsync().then(function (files) {
    var promises = [];
    files.forEach(function (file) {
        promises.push(WinJS.Promise.as(file));
        promises.push(file.getBasicPropertiesAsync());
    })
    return WinJS.Promise.join(promises);
})
.done(function (results) {
    var counter = 0

    while (counter < results.length) {
        var file = results[counter];
        var props = results[counter + 1];
        outString += "File name: " + file.name + "<br/>";
        outString += "File type: " + file.fileType + "<br/>";
        outString += "File size: " + props.size + "<br/>";
        outString += "<br/>"
        counter = counter + 2;
    }
});

This screen shot from the companion sample shows an example of getting various top-level and basic file properties.

File-handling sample screen shot of getting the properties of files.

Find it in the sample: The sample includes a page titled FileAccessBasics, which includes the examples presented in this section. The relevant JavaScript and HTML code is centralized to the FileAccessBasicsPage.js (OnGetFilePropertiesClick function) and FileAccessBasicsPage.html files.

step icon

Quickstart: Reading and writing a file

A Windows Store app reads and writes files via the FileIO class. See Quickstart: Reading and writing a file for code examples that show how to read and write various types of data using the FileIO and StorageFile classes.

Dn595121.wedge(en-us,WIN.10).gifWriting text to a file

  1. To write to a file, you must first acquire a StorageFile object to pass to one of the FileIO functions for writing data. In the companion sample, this is done by creating a file via the StorageFolder.createFileAsync function.
  2. Once you have a StorageFile object, you can write text to it underlying file via one of the overloaded FileIO.writeTextAsync functions.
This code example writes the current date/time to a sample file.

// Create the sample file; replacing it if it already exists.
var lib = Windows.Storage.KnownFolders.picturesLibrary;
lib.createFileAsync("FileHandlingJs.txt", 
    Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (file) {
    if (file) {
        // Format a string based on the current data/time.
        var now = new Date();
        var sampleFileContents = 
            [[now.getMonth() + 1, now.getDate(), now.getFullYear()].join("/"),
            [now.getHours(), AddZero(now.getMinutes())].join(":"),
            now.getHours() >= 12 ? "PM" : "AM"].join(" ");

        // Write the text to the sample file.
        Windows.Storage.FileIO.writeTextAsync(file, sampleFileContents)
        .then(function () {
            // File's contents have been written at this point.
        }, 
        function (error) {
            // Handle error.
        });
    }
});

Dn595121.wedge(en-us,WIN.10).gifReading text from a file

  1. To read the contents of a file, you must first acquire a StorageFile object to pass to one of the FileIO functions for reading data. In the companion sample, this is done by calling the StorageFolder.getFileAsync function.
  2. Once you have a StorageFile object, you can read text from its underlying file via one of the overloaded FileIO.readTextAsync functions.
This code example reads the contents from a sample file.

// Open sample file.
Windows.Storage.KnownFolders.picturesLibrary.getFileAsync("FileHandlingJs.txt")
.then(function (file) {
    // If file found ...
    if (file) {
        // Read file's contents.
        Windows.Storage.FileIO.readTextAsync(file).then(function (contents) {
            // Process file contents as needed.
        });
    }
}, function (error) {
    // Handle error.
});

This screen shot shows an example of running the sample and writing to the sample file.

File-handling sample screen shot of writing text data to a file.

Find it in the sample: The sample includes a page titled FileAccessBasics, which includes the samples presented in this section. The relevant JavaScript and HTML code is centralized to the FileAccessBasicsPage.js (OnWriteTextToFileClick and OnReadTextFromFileClick functions) and FileAccessBasicsPage.html files.

 

Working with file and folder pickers

step icon

Quickstart: Accessing files with file pickers

Pickers—both file pickers and folder pickers—are used to display a list of files or folders from which users can select one or more items for further processing. Pickers can be configured programmatically to search for files and folders that match a specified filter (such as files with specific extensions), start at a particular folder, display a specific view mode (list or thumbnail), and much more.

The following procedures show you how to configure the various pickers for single-file, multiple-file, and single-folder selection.

Dn595121.wedge(en-us,WIN.10).gifConfiguring a single-file selection file picker

  1. Instantiate a FileOpenPicker object.
  2. Set the FileOpenPicker object's viewMode, suggestedStartLocation, and fileTypeFilter properties as needed.
  3. Call the FileOpenPicker.pickSingleFileAsync function. When the FileOpenPicker.pickSingleFileAsync function is complete, the app has read/write access to the selected file.
This code example instantiates and displays a file picker for single-file selection.

// Instantiate a FileOpenPicker object.
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

// Set the FileOpenPicker object's key properties.
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;

openPicker.suggestedStartLocation = 
    Windows.Storage.Pickers.PickerLocationId.picturesLibrary;

openPicker.fileTypeFilter.replaceAll([".jpg", ".jpeg", ".png" ]);

// Display the FileOpenPicker for single file selection.
openPicker.pickSingleFileAsync().then(function (file) {
    // If the user selected a file ...
    if (file) {
        // ... process file as needed.
    }
    else {
        // User canceled the operation.
    }
});

Dn595121.wedge(en-us,WIN.10).gifConfiguring a multiple-file selection file picker

  1. Instantiate a FileOpenPicker object.
  2. Set the FileOpenPicker object's FileOpenPicker.viewMode, FileOpenPicker.suggestedStartLocation, and FileOpenPicker.FileTypeFilter properties as needed.
  3. Call the FileOpenPicker.pickMultipleFileAsync function. When the FileOpenPicker.pickMultipleFileAsync function is complete, the app has read/write access to the selected files. The files selected are represented by an array of StorageFile objects. The array's sizes property tells you how many files were selected, so you can use a for loop with standard array notation to access each StorageFile object.
This code example instantiates and displays a file picker for multiple-file selection.

// Instantiate a FileOpenPicker object.
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

// Set the FileOpenPicker object's key properties.
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;

openPicker.suggestedStartLocation = 
    Windows.Storage.Pickers.PickerLocationId.picturesLibrary;

openPicker.fileTypeFilter.replaceAll([".jpg", ".jpeg", ".png"]);

// Display the FileOpenPicker for multiple-file selection.
openPicker.pickMultipleFilesAsync().then(function (files) {
    // If the user selected at least one file ...
    if (files.size > 0) {
        for (var i = 0; i < files.size; i++) {
            // ... process each file - For example, files[i]
        }
    }
    else {
        // User canceled the operation.
    }
});

Dn595121.wedge(en-us,WIN.10).gifConfiguring a folder picker

  1. Instantiate a FolderPicker object.
  2. Set the FolderPicker object's FolderPicker.viewMode, FolderPicker.suggestedStartLocation, and FolderPicker.fileTypeFilter properties as needed.
  3. Call the FileOpenPicker.pickSingleFileAsync function. When the FolderPicker.pickSingleFolderAsync function is complete, the app has read/write access to the selected folder, including subfolders.
This code example instantiates and displays a folder picker.

// Instantiate a FolderPicker object.
var folderPicker = new Windows.Storage.Pickers.FolderPicker();

// Set the FileOpenPicker object's key properties.
folderPicker.suggestedStartLocation = 
    Windows.Storage.Pickers.PickerLocationId.desktop;
folderPicker.fileTypeFilter.replaceAll([".docx", ".xlsx", ".pptx"]);

// Display the FolderPicker for folder selection.
folderPicker.pickSingleFolderAsync().then(function (folder) {
    // If the user selected a folder ...
    if (folder) {
        // ... get the folder object.
        Windows.Storage.AccessCache.StorageApplicationPermissions.
        futureAccessList.addOrReplace("PickedFolderToken", folder);
        // Process folder as needed.
    }
    else {
        // User canceled operation.
    }
});

This screen shot shows the results of running the sample and selecting two files (sample1.png and sample2.png).

File-handling sample screen shot of using file and folder pickers.

Find it in the sample: The sample includes a page titled File and Folder Pickers that demonstrates the tasks outlined in this section. The JavaScript code and HTML for this sample is in the FilePickerPage.js and FilePickerPage.html files, respectively.

 

Working with OneDrive files

step icon

Quickstart: Determining availability of OneDrive files

Windows 8.1 enables users to mark OneDrive files as online only. When the user is disconnected from OneDrive, these files are not available. To help you programmatically determine the availability of a file, there's a new property called StorageFile.isAvailable.

These steps show you how to determine the availability of files using the StorageFile.isAvailable property.

  1. Acquire a StorageFolder object for the location you want. For example, you can do this by referencing one of the static KnownFolders properties, such as KnowFolders.picturesLibrary.
  2. Call the returned StorageFolder object's StorageFolder.getFilesAsync function. This topic's companion sample calls this method without any parameters, indicating that all files should be returned. To see examples of calling the StorageFolder.getFilesAsync with a query, refer to Quickstart: Accessing files programmatically.
  3. Once the StorageFolder.getFilesAsync function is complete, you can use a forEach loop to iterate over each returned file.
This code example enumerates all files in Pictures, displaying each file's name, provider name, and availability.

// Get a StorageFolder object representing Pictures.
var library = Windows.Storage.KnownFolders.picturesLibrary;

// Initialize string that will contain the file name, provider name, 
// and availability for each file.
var outString = "";

// Get all files from the StorageFolder object.
library.getFilesAsync().then(function (files) {
    // For each file found ...
    files.forEach(function (file) {
        // Retrieve the file's name, provider name, and availability.
        outString += file.name 
                  + " (on " 
                  + file.provider.displayName 
                  + ") is " 
                  + (file.isAvailable ? "available" : "not available") + "\n";
    });
});

This screen shot shows sample results of checking the files in Pictures for availability.

File-handling sample screen shot of working with OneDrive files.

Find it in the sample: The sample includes a page titled "OneDriveFilesPage", which has a button that enumerates all of the files in the local machine's Pictures. Each file name is displayed along with that file's provider (for example, This PC or OneDrive), and whether or not the file is currently available. The JavaScript code and HTML for this sample are in the OneDriveFilesPage.js and OneDriveFilesPage.html files, respectively.

 

Finish up

store requirements icon

Using the Windows App Certification Kit

Recommended. Running the Windows App Certification Kit helps you make sure that your app fulfills Windows Store requirements. We recommend you run it whenever you add major functionality to your app.

stop icon

You’re finished! Now that you’ve explored different file-handling capabilities for your app, you're ready to create an app like the File handling, start to finish companion sample.

 

Want to know more?

Quickstart: Asynchronous programming in JavaScript

Learn more about asynchronous programming in JavaScript.

Quickstart: Accessing files programmatically

Learn more about enumerating files.

Quickstart: Reading and writing a file

Learn more about reading and writing files.